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
Imports System.Reflection
Imports System.ComponentModel.Design
Imports Microsoft.VisualBasic

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 和 unmanaged 呼叫慣例。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
Imports System.Reflection
Imports Microsoft.VisualBasic

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

備註

針對GetFields(BindingFlags)若要成功擷取屬性資訊的多載bindingAttr引數必須包含至少一個BindingFlags.InstanceBindingFlags.Static,以及至少一個BindingFlags.NonPublicBindingFlags.PublicFor 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.

另請參閱

適用於