C#类的属性遍历及属性值获取
2021-03-31 17:26
标签:遍历 sys read 完整 type int 显示 system prope 1、定义一个类 2、获取属性 方法一、定义一个类的对象获取 方法二、通过类获取 3、通过属性名获取对象属性值 4、完整代码及结果显示 C#类的属性遍历及属性值获取 标签:遍历 sys read 完整 type int 显示 system prope 原文地址:https://www.cnblogs.com/zwcoding/p/9251310.htmlpublic class Person
{
public string Name { get; set; }
public int ID { get; set; }
}
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);
}
p.Name = "张三";
var name = p.GetType().GetProperty("Name").GetValue(p, null);
Console.WriteLine(name);
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();