Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức Type.GetField() trong C#

Phương thức Type.GetField() trong C# lấy một trường (field) cụ thể của Type hiện tại.

Cú pháp

public System.Reflection.FieldInfo GetField(string name);
public abstract System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr);

Tham số name là tên trường dữ liệu. bindingAttr chỉ định cách tìm kiếm.

Ví dụ 1

using System;
using System.Reflection;
public class Demo
{
    public static void Main()
    {
        Type type = typeof(Subject);
        try
        {
            FieldInfo fieldInfo = type.GetField("SubName");
            Console.WriteLine("FieldInfo = {0}", fieldInfo);
        }
        catch (ArgumentNullException e)
        {
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
public class Subject
{
    public string SubName = "Science";
}

Đầu ra

FieldInfo = System.String SubName

Ví dụ 2

using System;
using System.Reflection;
public class Demo
{
    public static void Main()
    {
        Type type = typeof(Subject);
        try
        {
            FieldInfo fieldInfo = type.GetField(null);
            Console.WriteLine("FieldInfo = {0}", fieldInfo);
        }
        catch (ArgumentNullException e)
        {
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
public class Subject
{
    public string SubName = "Science";
}

Đầu ra

System.ArgumentNullException