Computer >> 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 # được sử dụng để lấy một trường cụ thể của Kiểu hiện tại.

Cú pháp

Sau đây là cú pháp -

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

Ở trên, tên là chuỗi chứa tên của trường dữ liệu cần lấy. Tham số bindAttr là sự kết hợp theo từng bit của các giá trị liệt kê chỉ định cách tìm kiếm được tiến hành.

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ để triển khai phương thức Type.GetField () -

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

Điều này sẽ tạo ra kết quả sau -

FieldInfo = System.String SubName

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ khác để triển khai phương thức Type.GetField () -

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

Điều này sẽ tạo ra kết quả sau -

System.ArgumentNullException