System.Type.GetField 方法 (String)

方法描述

搜索具有指定名称的公共字段。

语法定义(C# System.Type.GetField 方法 (String) 的用法)

public FieldInfo GetField(
	string name
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
name System-String 包含要获取的数据字段的名称的字符串。
返回值 System.Reflection.FieldInfo 如找到,则为表示具有指定名称的公共字段的对象;否则为 null。

提示和注释

对 name 的搜索区分大小写。 搜索范围包括公共静态和公共实例字段。

如果当前 Type 表示构造泛型类型,则此方法将返回 FieldInfo,并且其类型形参替换为相应的类型实参。

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

System.Type.GetField 方法 (String)例子

下面的示例获取指定类的 Type 对象,获取字段的 FieldInfo 对象,然后显示该字段的值。

using System;
using System.Reflection;

public class MyFieldClassA
{
    public string Field = "A Field";
}

public class MyFieldClassB
{
    private string field = "B Field";
    public string Field 
    {
        get
        {
            return field;
        }
        set
        {
            if (field!=value)
            {
                field=value;
            }
        }
    }
}

public class MyFieldInfoClass
{
    public static void Main()
    {
        MyFieldClassB myFieldObjectB = new MyFieldClassB();
        MyFieldClassA myFieldObjectA = new MyFieldClassA();

        Type myTypeA = typeof(MyFieldClassA);
        FieldInfo myFieldInfo = myTypeA.GetField("Field");

        Type myTypeB = typeof(MyFieldClassB);
        FieldInfo myFieldInfo1 = myTypeB.GetField("field", 
            BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine("The value of the public field is: '{0}'", 
            myFieldInfo.GetValue(myFieldObjectA));
        Console.WriteLine("The value of the private field is: '{0}'", 
            myFieldInfo1.GetValue(myFieldObjectB));
    }
}

异常

异常 异常描述
ArgumentNullException name 为 null。
NotSupportedException 该 Type 对象为 TypeBuilder,其 CreateType 方法尚未被调用。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。