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 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. 按名称和签名隐藏会考虑所有的签名,包括自定义修饰符,部分返回类型、 参数类型、 标记和非托管调用约定。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) 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-

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

另请参阅

适用于