通过C#中的type类获取类中的字段、属性、方法等相关信息。
/// <summary> /// 通过type类获取类中的公有字段,属性和方法 /// </summary> /// class newClass { public string Id01; public string Id02; public string Id03; public string Name01 { get; set; } public string Name02 { get; set; } public string Name03 { get; set; } public void Method01() { } public void Method02() { } public void Method03() { } } class Program { static void Main(string[] args) { newClass testClass = new ReflectionTest01.newClass(); testClass.Id01 = "01"; testClass.Id02 = "02"; testClass.Id03 = "03"; testClass.Name01 = "name01"; testClass.Name02 = "name02"; testClass.Name03 = "name03"; Type type = testClass.GetType(); //获取基本属性 //获取类名 Console.WriteLine(type.Name); //获取命名空间 Console.WriteLine(type.Namespace); //获取命名空间 Console.WriteLine(type.Assembly); //获取public的字段 FieldInfo[] fields = type.GetFields(); foreach(FieldInfo info in fields) { Console.Write(info.Name+" "); Console.Write(info.GetValue(testClass)+ " "); } Console.WriteLine(); //获取属性 PropertyInfo[] props = type.GetProperties(); foreach (PropertyInfo info in props) { Console.Write(info.Name + " "); Console.Write(info.GetValue(testClass)+ " ");//获取对应的值 } Console.WriteLine(); //获取方法 MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo info in methods) { Console.Write(info.Name + " "); } Console.WriteLine(); Console.ReadKey(); } }
可以通过EventInfo[] events=type.GetEvents();获取类的事件。
时间: 2024-10-07 05:29:47