Type.GetFields Type.GetFields Type.GetFields Type.GetFields Method

定義

取得目前 Type 的欄位。Gets the fields of the current Type.

多載

GetFields() GetFields() GetFields() GetFields()

傳回目前 Type 的所有公用欄位。Returns all the public fields of the current Type.

GetFields(BindingFlags) GetFields(BindingFlags) GetFields(BindingFlags) GetFields(BindingFlags)

在衍生類別中覆寫時,使用指定的繫結條件約束,搜尋定義給目前 Type 的欄位。When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints.

GetFields() GetFields() GetFields() GetFields()

傳回目前 Type 的所有公用欄位。Returns all the public fields of the current Type.

public:
 virtual cli::array <System::Reflection::FieldInfo ^> ^ GetFields();
public System.Reflection.FieldInfo[] GetFields ();
abstract member GetFields : unit -> System.Reflection.FieldInfo[]
override this.GetFields : unit -> System.Reflection.FieldInfo[]
Public Function GetFields () As FieldInfo()

傳回

FieldInfo 物件的陣列,代表為目前 Type 定義的所有公用欄位。An array of FieldInfo objects representing all the public fields defined for the current Type.

-或--or- FieldInfo 類型的空陣列 (如果沒有為目前 Type 定義公用欄位)。An empty array of type FieldInfo, if no public fields are defined for the current Type.

實作

範例

下列範例示範如何使用GetFields()方法。The following example shows a use of the GetFields() method.

#using <system.dll>

using namespace System;
using namespace System::Reflection;
using namespace System::ComponentModel::Design;

int main()
{
   try
   {
      // Get the type handle of a specified class.
      Type^ myType = ViewTechnology::typeid;

      // Get the fields of the specified class.
      array<FieldInfo^>^myField = myType->GetFields();
      Console::WriteLine( "\nDisplaying fields that have SpecialName attributes:\n" );
      for ( int i = 0; i < myField->Length; i++ )
      {
         // Determine whether or not each field is a special name.
         if ( myField[ i ]->IsSpecialName )
         {
            Console::WriteLine( "The field {0} has a SpecialName attribute.", myField[ i ]->Name );
         }
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception : {0} ", e->Message );
   }
}
using System;
using System.Reflection;
using System.ComponentModel.Design;


class FieldInfo_IsSpecialName
{
    public static void Main()
    {     
        try
        {
            // Get the type handle of a specified class.
            Type myType = typeof(ViewTechnology);
         
            // Get the fields of the specified class.
            FieldInfo[] myField = myType.GetFields();

            Console.WriteLine("\nDisplaying fields that have SpecialName attributes:\n");
            for(int i = 0; i < myField.Length; i++)
            {
                // Determine whether or not each field is a special name.
                if(myField[i].IsSpecialName)
                {
                    Console.WriteLine("The field {0} has a SpecialName attribute.",
                        myField[i].Name);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception : {0} " , e.Message);
        }
    }
}
Imports System.Reflection
Imports System.ComponentModel.Design

Class FieldInfo_IsSpecialName

    Public Shared Sub Main()
        Try
            ' Get the type handle of a specified class.
            Dim myType As Type = GetType(ViewTechnology)

            ' Get the fields of a specified class.
            Dim myField As FieldInfo() = myType.GetFields()

            Console.WriteLine(ControlChars.Cr + "Displaying fields that have SpecialName attributes:" + ControlChars.Cr)
            Dim i As Integer
            For i = 0 To myField.Length - 1
                ' Determine whether or not each field is a special name.
                If myField(i).IsSpecialName Then
                    Console.WriteLine("The field {0} has a SpecialName attribute.", myField(i).Name)
                End If
            Next i
        Catch e As Exception
            Console.WriteLine("Exception : {0} ", e.Message.ToString())
        End Try
    End Sub 'Main
End Class 'FieldInfo_IsSpecialName

備註

GetFields方法不會以特定順序傳回欄位,例如依字母順序或宣告順序。The GetFields method does not return fields in a particular order, such as alphabetical or declaration order. 您的程式碼不能相依于傳回欄位的順序,因為該順序會有所不同。Your code must not depend on the order in which fields are returned, because that order varies.

下表顯示當在類型上反映時, 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 No No
欄位Field No 可以。Yes. 欄位一律會依名稱和簽章隱藏。A field is always hide-by-name-and-signature.
Event - 事件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.

如果目前Type的表示結構化的泛型型別,這個方法FieldInfo會傳回具有類型參數的物件,並由適當的類型引數取代。If the current Type represents a constructed generic type, this method returns the FieldInfo objects 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 public fields of the class constraint.

另請參閱

GetFields(BindingFlags) GetFields(BindingFlags) GetFields(BindingFlags) GetFields(BindingFlags)

在衍生類別中覆寫時,使用指定的繫結條件約束,搜尋定義給目前 Type 的欄位。When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints.

public:
 abstract cli::array <System::Reflection::FieldInfo ^> ^ GetFields(System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo[] GetFields (System.Reflection.BindingFlags bindingAttr);
abstract member GetFields : System.Reflection.BindingFlags -> System.Reflection.FieldInfo[]
Public MustOverride Function GetFields (bindingAttr As BindingFlags) As FieldInfo()

參數

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

列舉值的位元組合,用來指定搜尋的執行方式。A bitwise combination of the enumeration values that specify how the search is conducted.

-或--or-

要傳回空陣列的 DefaultDefault to return an empty array.

傳回

FieldInfo 物件的陣列,代表為目前 Type 定義之符合指定繫結條件約束的所有欄位。An array of FieldInfo objects representing all fields defined for the current Type that match the specified binding constraints.

-或--or- 如果沒有任何欄位定義給目前 FieldInfo 的欄位,或沒有已定義的欄位符合繫結條件約束,則為 Type 類型的空陣列。An empty array of type FieldInfo, if no fields are defined for the current Type, or if none of the defined fields match the binding constraints.

實作

範例

下列範例示範如何使用GetFields(BindingFlags)方法。The following example shows a use of the GetFields(BindingFlags) method.

using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::InteropServices;
public ref class AttributesSample
{
public:
   void Mymethod( int int1m, [Out]interior_ptr<String^> str2m, interior_ptr<String^> str3m )
   {
       *str2m = "in Mymethod";
   }
};

void PrintAttributes( Type^ attribType, int iAttribValue )
{
   if (  !attribType->IsEnum )
   {
      Console::WriteLine( "This type is not an enum." );
      return;
   }

   array<FieldInfo^>^fields = attribType->GetFields( static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Static) );
   for ( int i = 0; i < fields->Length; i++ )
   {
      int fieldvalue = safe_cast<Int32>(fields[ i ]->GetValue( nullptr ));
      if ( (fieldvalue & iAttribValue) == fieldvalue )
      {
         Console::WriteLine( fields[ i ]->Name );
      }
   }
}

int main()
{
   Console::WriteLine( "Reflection.MethodBase.Attributes Sample" );

   // Get the type.
   Type^ MyType = Type::GetType( "AttributesSample" );

   // Get the method Mymethod on the type.
   MethodBase^ Mymethodbase = MyType->GetMethod( "Mymethod" );

   // Display the method name.
   Console::WriteLine( "Mymethodbase = {0}", Mymethodbase );

   // Get the MethodAttribute enumerated value.
   MethodAttributes Myattributes = Mymethodbase->Attributes;

   // Display the flags that are set.
   PrintAttributes( System::Reflection::MethodAttributes::typeid, (int)Myattributes );
   return 0;
}

using System;
using System.Reflection;
 
class AttributesSample
{
    public void Mymethod (int int1m, out string str2m, ref string str3m)
    {
        str2m = "in Mymethod";
    }
 
    public static int Main(string[] args)
    {      
        Console.WriteLine ("Reflection.MethodBase.Attributes Sample");
       
        // Get the type.
        Type MyType = Type.GetType("AttributesSample");
 
        // Get the method Mymethod on the type.
        MethodBase Mymethodbase = MyType.GetMethod("Mymethod");
 
        // Display the method name.
        Console.WriteLine("Mymethodbase = " + Mymethodbase);
 
        // Get the MethodAttribute enumerated value.
        MethodAttributes Myattributes = Mymethodbase.Attributes;
 
        // Display the flags that are set.
        PrintAttributes(typeof(System.Reflection.MethodAttributes), (int) Myattributes);
        return 0;
    }
 
 
    public static void PrintAttributes(Type attribType, int iAttribValue)
    {
        if (!attribType.IsEnum)
        { 
            Console.WriteLine("This type is not an enum."); 
            return; 
        }
 
        FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
        for (int i = 0; i < fields.Length; i++)
        {
            int fieldvalue = (Int32)fields[i].GetValue(null);
            if ((fieldvalue & iAttribValue) == fieldvalue)
            {
                Console.WriteLine(fields[i].Name);
            }
        }
    }
}
Imports System.Reflection

Class AttributesSample

    Public Sub Mymethod(ByVal int1m As Integer, ByRef str2m As String, ByRef str3m As String)
        str2m = "in Mymethod"
    End Sub 'Mymethod

    Public Shared Function Main(ByVal args() As String) As Integer
        Console.WriteLine("Reflection.MethodBase.Attributes Sample")

        ' Get the type.
        Dim MyType As Type = Type.GetType("AttributesSample")

        ' Get the method Mymethod on the type.
        Dim Mymethodbase As MethodBase = MyType.GetMethod("Mymethod")

        ' Display the method name.
        Console.WriteLine("Mymethodbase = {0}.", Mymethodbase)

        ' Get the MethodAttribute enumerated value.
        Dim Myattributes As MethodAttributes = Mymethodbase.Attributes

        ' Display the flags that are set.
        PrintAttributes(GetType(System.Reflection.MethodAttributes), CInt(Myattributes))
        Return 0
    End Function 'Main

    Public Shared Sub PrintAttributes(ByVal attribType As Type, ByVal iAttribValue As Integer)
        If Not attribType.IsEnum Then
            Console.WriteLine("This type is not an enum.")
            Return
        End If
        Dim fields As FieldInfo() = attribType.GetFields((BindingFlags.Public Or BindingFlags.Static))
        Dim i As Integer
        For i = 0 To fields.Length - 1
            Dim fieldvalue As Integer = CType(fields(i).GetValue(Nothing), Int32)
            If (fieldvalue And iAttribValue) = fieldvalue Then
                Console.WriteLine(fields(i).Name)
            End If
        Next i
    End Sub 'PrintAttributes
End Class 'AttributesSample

備註

BindingFlags.Static BindingFlags.Instance bindingAttr BindingFlags.Public BindingFlags.NonPublic若要讓多載成功取得屬性資訊,引數必須包含至少一個和,以及至少一個和。 GetFields(BindingFlags)For the GetFields(BindingFlags) overload to successfully retrieve property information, the bindingAttr argument must include at least one of BindingFlags.Instance and BindingFlags.Static, along with at least one of BindingFlags.NonPublic and BindingFlags.Public.

下列BindingFlags篩選旗標可以用來定義要包含在搜尋中的欄位:The following BindingFlags filter flags can be used to define which fields to include in the search:

  • 指定BindingFlags.Instance以包含實例方法。Specify BindingFlags.Instance to include instance methods.

  • 指定BindingFlags.Static以包含靜態方法。Specify BindingFlags.Static to include static methods.

  • 指定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. 只會傳回基類上的受保護和內部欄位;不會傳回基類上的私用欄位。Only protected and internal fields on base classes are returned; private fields on base classes are not returned.

  • 指定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.Default指定以傳回空PropertyInfo陣列。Specify BindingFlags.Default alone to return an empty PropertyInfo array.

下列BindingFlags的修飾詞旗標可以用來變更搜尋的運作方式:The following BindingFlags modifier flags can be used to change how the search works:

  • 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.

GetFields方法不會以特定順序傳回欄位,例如依字母順序或宣告順序。The GetFields method does not return fields in a particular order, such as alphabetical or declaration order. 您的程式碼不能相依于傳回欄位的順序,因為該順序會有所不同。Your code must not depend on the order in which fields are returned, because that order varies.

如果目前Type的表示結構化的泛型型別,這個方法FieldInfo會傳回具有類型參數的物件,並由適當的類型引數取代。If the current Type represents a constructed generic type, this method returns the FieldInfo objects 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 public fields of the class constraint.

另請參閱

適用於