要获取C#中当前类型的特定字段,代码如下-
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"; }
输出结果
这将产生以下输出-
FieldInfo = System.String SubName
让我们看另一个例子-
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"; }
输出结果
这将产生以下输出-
System.ArgumentNullException