Type.GetField 方法

定义

获取当前 Type 的特定字段。Gets a specific field of the current Type.

重载

GetField(String)

搜索具有指定名称的公共字段。Searches for the public field with the specified name.

GetField(String, BindingFlags)

使用指定绑定约束搜索指定字段。Searches for the specified field, using the specified binding constraints.

GetField(String)

搜索具有指定名称的公共字段。Searches for the public field with the specified name.

public:
 virtual System::Reflection::FieldInfo ^ GetField(System::String ^ name);
public System.Reflection.FieldInfo GetField (string name);
abstract member GetField : string -> System.Reflection.FieldInfo
override this.GetField : string -> System.Reflection.FieldInfo
Public Function GetField (name As String) As FieldInfo

参数

name
String

包含要获取的数据字段的名称的字符串。The string containing the name of the data field to get.

返回

如找到,则为表示具有指定名称的公共字段的对象;否则为 nullAn object representing the public field with the specified name, if found; otherwise, null.

实现

异常

namenullname is null.

Type 对象是尚未调用其 CreateType() 方法的 TypeBuilderThis Type object is a TypeBuilder whose CreateType() method has not yet been called.

示例

下面的示例获取Type指定类的对象, FieldInfo获取该字段的对象,并显示该字段的值。The following example gets the Type object for the specified class, obtains the FieldInfo object for the field, and displays the value of the field.

using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyFieldClassA
{
public:
   String^ field;
   MyFieldClassA()
   {
      field = "A Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

public ref class MyFieldClassB
{
public:
   String^ field;
   MyFieldClassB()
   {
      field = "B Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

int main()
{
   try
   {
      MyFieldClassB^ myFieldObjectB = gcnew MyFieldClassB;
      MyFieldClassA^ myFieldObjectA = gcnew MyFieldClassA;
      Type^ myTypeA = Type::GetType( "MyFieldClassA" );
      FieldInfo^ myFieldInfo = myTypeA->GetField( "field" );
      Type^ myTypeB = Type::GetType( "MyFieldClassB" );
      FieldInfo^ myFieldInfo1 = myTypeB->GetField( "field", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo->GetValue( myFieldObjectA ) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo1->GetValue( myFieldObjectB ) );
   }
   catch ( SecurityException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }

}


using System;
using System.Reflection;

public class MyFieldClassA
{
    public string Field = "A Field";
}

public class MyFieldClassB
{
    private string field = "B Field";
    public string Field 
    {
        get
        {
            return field;
        }
        set
        {
            if (field!=value)
            {
                field=value;
            }
        }
    }
}

public class MyFieldInfoClass
{
    public static void Main()
    {
        MyFieldClassB myFieldObjectB = new MyFieldClassB();
        MyFieldClassA myFieldObjectA = new MyFieldClassA();

        Type myTypeA = typeof(MyFieldClassA);
        FieldInfo myFieldInfo = myTypeA.GetField("Field");

        Type myTypeB = typeof(MyFieldClassB);
        FieldInfo myFieldInfo1 = myTypeB.GetField("field", 
            BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine("The value of the public field is: '{0}'", 
            myFieldInfo.GetValue(myFieldObjectA));
        Console.WriteLine("The value of the private field is: '{0}'", 
            myFieldInfo1.GetValue(myFieldObjectB));
    }
}

Imports System.Reflection

Public Class MyFieldClassA
    Public Field As String = "A Field"
End Class

Public Class MyFieldClassB
    Private myField As String = "B Field"

    Public Property Field() As String
        Get
            Return myField
        End Get
        Set(ByVal Value As String)
            If myField <> value Then
                myField = value
            End If
        End Set
    End Property
End Class


Public Class MyFieldInfoClass

    Public Shared Sub Main()
        Dim myFieldObjectB As New MyFieldClassB()
        Dim myFieldObjectA As New MyFieldClassA()

        Dim myTypeA As Type = GetType(MyFieldClassA)
        Dim myFieldInfo As FieldInfo = myTypeA.GetField("Field")

        Dim myTypeB As Type = GetType(MyFieldClassB)
        Dim myFieldInfo1 As FieldInfo = myTypeB.GetField("myField", _
            BindingFlags.NonPublic Or BindingFlags.Instance)

        Console.WriteLine("The value of the public field is: '{0}'", _
            myFieldInfo.GetValue(myFieldObjectA))
        Console.WriteLine("The value of the private field is: '{0}'", _
            myFieldInfo1.GetValue(myFieldObjectB))
    End Sub

End Class

注解

的搜索name区分大小写。The search for name is case-sensitive. 搜索包括公共静态和公共实例字段。The search includes public static and public instance fields.

如果当前Type表示构造泛型类型,则此方法将FieldInfo返回,并将类型参数替换为相应的类型参数。If the current Type represents a constructed generic type, this method returns the FieldInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法的定义中的类型参数,则此方法会搜索类约束的字段。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the fields of the class constraint.

另请参阅

GetField(String, BindingFlags)

使用指定绑定约束搜索指定字段。Searches for the specified field, using the specified binding constraints.

public:
 abstract System::Reflection::FieldInfo ^ GetField(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo GetField (string name, System.Reflection.BindingFlags bindingAttr);
abstract member GetField : string * System.Reflection.BindingFlags -> System.Reflection.FieldInfo
Public MustOverride Function GetField (name As String, bindingAttr As BindingFlags) As FieldInfo

参数

name
String

包含要获取的数据字段的名称的字符串。The string containing the name of the data field to get.

bindingAttr
BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted.

-or- 若为 Default,则返回 nullDefault to return null.

返回

表示符合指定需求的字段的对象(如果找到的话);否则为 nullAn object representing the field that matches the specified requirements, if found; otherwise, null.

实现

异常

namenullname is null.

示例

下面的示例获取Type指定类的对象, FieldInfo获取与指定绑定标志匹配的字段的对象,并显示该字段的值。The following example gets the Type object for the specified class, obtains the FieldInfo object for the field that matches the specified binding flags, and displays the value of the field.

using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyFieldClassA
{
public:
   String^ field;
   MyFieldClassA()
   {
      field = "A Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

public ref class MyFieldClassB
{
public:
   String^ field;
   MyFieldClassB()
   {
      field = "B Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

int main()
{
   try
   {
      MyFieldClassB^ myFieldObjectB = gcnew MyFieldClassB;
      MyFieldClassA^ myFieldObjectA = gcnew MyFieldClassA;
      Type^ myTypeA = Type::GetType( "MyFieldClassA" );
      FieldInfo^ myFieldInfo = myTypeA->GetField( "field" );
      Type^ myTypeB = Type::GetType( "MyFieldClassB" );
      FieldInfo^ myFieldInfo1 = myTypeB->GetField( "field", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo->GetValue( myFieldObjectA ) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo1->GetValue( myFieldObjectB ) );
   }
   catch ( SecurityException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }

}


using System;
using System.Reflection;

public class MyFieldClassA
{
    public string Field = "A Field";
}

public class MyFieldClassB
{
    private string field = "B Field";
    public string Field 
    {
        get
        {
            return field;
        }
        set
        {
            if (field!=value)
            {
                field=value;
            }
        }
    }
}

public class MyFieldInfoClass
{
    public static void Main()
    {
        MyFieldClassB myFieldObjectB = new MyFieldClassB();
        MyFieldClassA myFieldObjectA = new MyFieldClassA();

        Type myTypeA = typeof(MyFieldClassA);
        FieldInfo myFieldInfo = myTypeA.GetField("Field");

        Type myTypeB = typeof(MyFieldClassB);
        FieldInfo myFieldInfo1 = myTypeB.GetField("field", 
            BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine("The value of the public field is: '{0}'", 
            myFieldInfo.GetValue(myFieldObjectA));
        Console.WriteLine("The value of the private field is: '{0}'", 
            myFieldInfo1.GetValue(myFieldObjectB));
    }
}

Imports System.Reflection

Public Class MyFieldClassA
    Public Field As String = "A Field"
End Class

Public Class MyFieldClassB
    Private myField As String = "B Field"

    Public Property Field() As String
        Get
            Return myField
        End Get
        Set(ByVal Value As String)
            If myField <> value Then
                myField = value
            End If
        End Set
    End Property
End Class


Public Class MyFieldInfoClass

    Public Shared Sub Main()
        Dim myFieldObjectB As New MyFieldClassB()
        Dim myFieldObjectA As New MyFieldClassA()

        Dim myTypeA As Type = GetType(MyFieldClassA)
        Dim myFieldInfo As FieldInfo = myTypeA.GetField("Field")

        Dim myTypeB As Type = GetType(MyFieldClassB)
        Dim myFieldInfo1 As FieldInfo = myTypeB.GetField("myField", _
            BindingFlags.NonPublic Or BindingFlags.Instance)

        Console.WriteLine("The value of the public field is: '{0}'", _
            myFieldInfo.GetValue(myFieldObjectA))
        Console.WriteLine("The value of the private field is: '{0}'", _
            myFieldInfo1.GetValue(myFieldObjectB))
    End Sub

End Class

注解

下表显示了在类型上反射时Get方法返回的基类成员。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成员类型Member Type StaticStatic 非静态Non-Static
构造函数Constructor NoNo NoNo
字段Field NoNo 可以。Yes. 字段始终按名称和签名隐藏。A field is always hide-by-name-and-signature.
事件Event 不适用Not applicable 通用类型系统规则是指继承与实现属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为隐藏的名称和签名。Reflection treats properties as hide-by-name-and-signature. 请参阅下面的注释2。See note 2 below.
方法Method NoNo 可以。Yes. 方法(虚拟和非虚拟)可按名称隐藏或按名称和签名隐藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
嵌套类型Nested Type NoNo NoNo
PropertyProperty 不适用Not applicable 通用类型系统规则是指继承与实现属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为隐藏的名称和签名。Reflection treats properties as hide-by-name-and-signature. 请参阅下面的注释2。See note 2 below.
  1. 按名称和签名隐藏将考虑签名的所有部分,包括自定义修饰符、返回类型、参数类型、个 sentinel 和非托管调用约定。Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. 这是二进制比较。This is a binary comparison.

  2. 对于反射,属性和事件是按名称和签名隐藏的。For reflection, properties and events are hide-by-name-and-signature. 如果在基类中同时具有 get 访问器和 set 访问器的属性,但派生类只有 get 访问器,则派生类属性将隐藏基类属性,并且你将无法访问基类的资源库。If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. 自定义属性不属于通用类型系统。Custom attributes are not part of the common type system.

以下BindingFlags筛选器标志可用于定义要包括在搜索中的字段:The following BindingFlags filter flags can be used to define which fields to include in the search:

  • 必须指定BindingFlags.InstanceBindingFlags.Static才能获取返回。You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • 指定BindingFlags.Public在搜索中包含公共字段。Specify BindingFlags.Public to include public fields in the search.

  • 指定BindingFlags.NonPublic以包括搜索中的非公共字段(即,私有字段、内部字段和受保护字段)。Specify BindingFlags.NonPublic to include non-public fields (that is, private, internal, and protected fields) in the search.

  • 指定BindingFlags.FlattenHierarchy在层次public结构protected中包含和静态成员;private不包括继承类中的静态成员。Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

以下BindingFlags修饰符标志可用于更改搜索的工作方式:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase如果忽略,则为nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly仅搜索在上Type声明的字段,而不搜索只是继承的字段。BindingFlags.DeclaredOnly to search only the fields declared on the Type, not fields that were simply inherited.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

如果当前Type表示构造泛型类型,则此方法将FieldInfo返回,并将类型参数替换为相应的类型参数。If the current Type represents a constructed generic type, this method returns the FieldInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示泛型类型或泛型方法的定义中的类型参数,则此方法会搜索类约束的字段。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the fields of the class constraint.

另请参阅

适用于