Type.GetFields 方法

定义

获取当前 Type 的字段。

重载

GetFields()

返回当前 Type 的所有公共字段。

GetFields(BindingFlags)

当在派生类中重写时,使用指定绑定约束,搜索为当前 Type 定义的字段。

GetFields()

返回当前 Type 的所有公共字段。

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

返回

表示为当前 FieldInfo 定义的所有公共字段的 Type 对象数组。

- 或 -

如果没有为当前 FieldInfo 定义的公共字段,则为 Type 类型的空数组。

实现

示例

以下示例演示 了 方法的 GetFields() 用法。

#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);
        }
    }
}
open System.ComponentModel.Design

try
    // Get the type handle of a specified class.
    let myType = typeof<ViewTechnology>

    // Get the fields of the specified class.
    let myFields = myType.GetFields()

    printfn $"\nDisplaying fields that have SpecialName attributes:\n"
    for field in myFields do
        // Determine whether or not each field is a special name.
        if field.IsSpecialName then
            printfn $"The field {field.Name} has a SpecialName attribute."
with e ->
    printfn $"Exception : {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 不返回特定顺序(例如字母顺序或声明顺序)的字段。 代码不得依赖于返回字段的顺序,因为该顺序会有所不同。

下表显示了在对类型进行反射时,方法将返回 Get 基类的哪些成员。

成员类型 静态 非静态
构造函数
字段 可以。 字段始终按名称和签名隐藏。
事件 不适用 常见的类型系统规则是继承与实现 属性的方法的继承相同。 反射将属性视为按名称和签名隐藏。 请参阅下面的说明 2。
方法 可以。 (虚拟和非虚拟) 的方法可以是按名称隐藏或按名称和签名隐藏。
嵌套类型
properties 不适用 常见的类型系统规则是继承与实现 属性的方法的继承相同。 反射将属性视为按名称和签名隐藏。 请参阅下面的说明 2。
  1. 按名称隐藏和签名考虑签名的所有部分,包括自定义修饰符、返回类型、参数类型、sentinels 和非托管调用约定。 这是二进制比较。

  2. 为了反射,属性和事件是按名称和签名隐藏的。 如果基类中有一个同时具有 get 和 set 访问器的属性,但派生类只有一个 get 访问器,则派生类属性将隐藏基类属性,并且你将无法访问基类上的 setter。

  3. 自定义属性不是通用类型系统的一部分。

如果当前 Type 表示构造的泛型类型,则此方法返回 FieldInfo 对象,其类型参数替换为相应的类型参数。

如果当前 Type 表示泛型类型或泛型方法的定义中的类型参数,则此方法将搜索类约束的公共字段。

另请参阅

适用于

GetFields(BindingFlags)

当在派生类中重写时,使用指定绑定约束,搜索为当前 Type 定义的字段。

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

枚举值的按位组合,这些值指定如何进行搜索。

- 或 -

若为 Default,则返回空数组。

返回

表示为当前 FieldInfo 定义的匹配指定绑定约束的所有字段的 Type 对象数组。

- 或 -

如果没有为当前 FieldInfo 定义的字段,或者如果没有一个定义的字段匹配绑定约束,则为 Type 类型的空数组。

实现

示例

以下示例演示 了 方法的 GetFields(BindingFlags) 用法。

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 = (int)fields[i].GetValue(null);
            if ((fieldvalue & iAttribValue) == fieldvalue)
            {
                Console.WriteLine(fields[i].Name);
            }
        }
    }
}
open System
open System.Reflection

type AttributesSample() =
    member _.Mymethod(int1m: int, str2m: string outref, str3m: string byref) =
        str2m <- "in Mymethod"

let printAttributes (attribType: Type) iAttribValue =
    if not attribType.IsEnum then
        printfn "This type is not an enum."
    else
        let fields = attribType.GetFields(BindingFlags.Public ||| BindingFlags.Static)
        for f in fields do
            let fieldvalue = f.GetValue null :?> int
            if fieldvalue &&& iAttribValue = fieldvalue then
                printfn $"{f.Name}"

printfn "Reflection.MethodBase.Attributes Sample"

// Get the type.
let MyType = Type.GetType "AttributesSample"

// Get the method Mymethod on the type.
let Mymethodbase = MyType.GetMethod "Mymethod"

// Display the method name.
printfn $"Mymethodbase = {Mymethodbase}"

// Get the MethodAttribute enumerated value.
let Myattributes = Mymethodbase.Attributes

// Display the flags that are set.
printAttributes typeof<MethodAttributes> (int Myattributes)
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

注解

GetFields(BindingFlags)要使重载成功检索属性信息,bindingAttr参数必须至少包含 和 BindingFlags.StaticBindingFlags.Instance一个 ,以及 至少一个 BindingFlags.NonPublicBindingFlags.Public

以下 BindingFlags 筛选标志可用于定义要在搜索中包括的字段:

  • 指定 BindingFlags.Instance 以包含实例方法。

  • 指定 BindingFlags.Static 以包含静态方法。

  • 指定 BindingFlags.Public 以在搜索中包含公共字段。

  • 指定 BindingFlags.NonPublic 以包括非公共字段 (,即搜索中) 私有字段、内部字段和受保护字段。 仅返回基类上的受保护字段和内部字段;不返回基类上的私有字段。

  • 指定要 BindingFlags.FlattenHierarchy 在层次结构中包括 publicprotected 静态成员; private 继承类中的静态成员不包括在层次结构中。

  • 单独指定 BindingFlags.Default 以返回空 PropertyInfo 数组。

以下 BindingFlags 修饰符标志可用于更改搜索的工作方式:

  • BindingFlags.DeclaredOnly 如果只搜索 上 Type声明的字段,则搜索只是继承的字段。

有关更多信息,请参见System.Reflection.BindingFlags

方法 GetFields 不返回特定顺序(例如字母顺序或声明顺序)的字段。 代码不得依赖于返回字段的顺序,因为该顺序会有所不同。

如果当前 Type 表示构造的泛型类型,则此方法返回 FieldInfo 对象,其类型参数替换为相应的类型参数。

如果当前 Type 表示泛型类型或泛型方法的定义中的类型参数,则此方法将搜索类约束的公共字段。

另请参阅

适用于