C#类的属性遍历及属性值获取
1、定义一个类
public class Person { public string Name { get; set; } public int ID { get; set; } }
2、获取属性
方法一、定义一个类的对象获取
Person p = new Person(); foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()) { Console.WriteLine(info.Name); }
方法二、通过类获取
var properties = typeof(Person).GetProperties(); foreach (System.Reflection.PropertyInfo info in properties) { Console.WriteLine(info.Name); }
3、通过属性名获取对象属性值
p.Name = "张三"; var name = p.GetType().GetProperty("Name").GetValue(p, null); Console.WriteLine(name);
4、完整代码及结果显示
var properties = typeof(Person).GetProperties(); foreach (System.Reflection.PropertyInfo info in properties) { Console.WriteLine(info.Name); } Console.WriteLine("另一种遍历属性的方法:"); Person p = new Person(); foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()) { Console.WriteLine(info.Name); } Console.WriteLine("通过属性值获取属性:"); p.Name = "张三"; var name = p.GetType().GetProperty("Name").GetValue(p, null); Console.WriteLine(name); Console.ReadLine();