Type.GetField Method

Definition

取得目前 Type 的特定欄位。Gets a specific field of the current Type.

Overloads

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

Parameters

name
String

字串,包含要取得的資料欄位的名稱。The string containing the name of the data field to get.

Returns

FieldInfo

物件,代表具有指定之名稱的公用欄位 (如有找到);否則為 nullAn object representing the public field with the specified name, if found; otherwise, null.

Implements

Exceptions

namenullname is null.

這個 Type 物件是 TypeBuilder,尚未呼叫其 CreateType() 方法。This Type object is a TypeBuilder whose CreateType() method has not yet been called.

Examples

下列範例會取得指定類別的 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

Remarks

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.

See also

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

Parameters

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- 要傳回 nullDefaultDefault to return null.

Returns

FieldInfo

代表符合指定之需求欄位的物件 (如有找到) ,否則為 nullAn object representing the field that matches the specified requirements, if found; otherwise, null.

Implements

Exceptions

namenullname is null.

Examples

下列範例會取得指定之類別的 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

Remarks

下表顯示當在類型上反映時,Get 方法傳回的基類成員。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成員類型Member Type 靜態Static 非靜態Non-Static
建構函式Constructor No No
欄位Field No 是。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 No 是。Yes. 方法(虛擬和非虛擬)可以依名稱或逐名稱和簽章來隱藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
巢狀型別Nested Type No No
屬性Property 不適用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. [逐名稱] 和 [簽章] 會考慮簽章的所有部分,包括自訂修飾詞、傳回類型、參數類型、sentinels 和非受控呼叫慣例。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 存取子,則衍生類別屬性會隱藏基類屬性,而且您將無法存取基類上的 setter。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.PublicSpecify BindingFlags.Public to include public fields in the search.

  • 指定要在搜尋中包含非公用欄位(也就是私用、內部和受保護的欄位) BindingFlags.NonPublicSpecify BindingFlags.NonPublic to include non-public fields (that is, private, internal, and protected fields) in the search.

  • 指定 BindingFlags.FlattenHierarchy 在階層中包含 publicprotected 靜態成員;不包含繼承類別中 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 以忽略 name的大小寫。BindingFlags.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.

See also

Applies to