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

Lấy field cụ thể của type hiện tại trong C#

Để lấy một field cụ thể của type hiện tại trong C#, ta dùng Type.GetField từ namespace System.Reflection. Dưới đây là các ví dụ.

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";
}

Kết quả

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";
}

Kết quả

System.ArgumentNullException