获取C#中当前Type的指定成员?
要获取当前Type的指定成员,代码如下-
示例
using System; using System.Reflection; public class Demo { public static void Main() { Type type = typeof(Subject); try { FieldInfo fieldInfo = type.GetField("SubName"); MemberInfo[] info = type.GetMember("SubName"); Console.Write("Members = "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); Console.WriteLine("FieldInfo = {0}", fieldInfo); } catch (ArgumentNullException e) { Console.Write("{0}", e.GetType(), e.Message); } } } public class Subject { public string SubName = "Science"; }
输出结果
这将产生以下输出-
Members = System.String SubName 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("SubName"); MemberInfo[] info = type.GetMember("SubName", BindingFlags.Public | BindingFlags.Instance); Console.Write("Members = "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); Console.WriteLine("FieldInfo = {0}", fieldInfo); } catch (ArgumentNullException e) { Console.Write("{0}", e.GetType(), e.Message); } } } public class Subject { public string SubName = "Science"; }
输出结果
这将产生以下输出-
Members = System.String SubName FieldInfo = System.String SubName