Type.GetFields 方法

定义

获取当前 Type 的字段。Gets the fields of the current Type.

重载

GetFields()

返回当前 Type 的所有公共字段。Returns all the public fields of the current Type.

GetFields(BindingFlags)

当在派生类中重写时,使用指定绑定约束,搜索为当前 Type 定义的字段。When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints.

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
End Class

注解

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

如果当前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)

当在派生类中重写时,使用指定绑定约束,搜索为当前 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

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

-or-

若为 Default,则返回空数组。Default 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

    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
End Class

注解

BindingFlags.NonPublic BindingFlags.Instance BindingFlags.Static BindingFlags.Public为了使bindingAttr重载成功检索属性信息,参数必须包含至少一个和,以及至少一个和中的一个。 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在层次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.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.

另请参阅

适用于