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、完整代码及结果显示
![复制代码](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jb21tb24uY25ibG9ncy5jb20vaW1hZ2VzL2NvcHljb2RlLmdpZg)
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();
Type t = tc.GetType();//获得该类的Type
//再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
foreach (PropertyInfo pi in t.GetProperties
{
object value1 = pi.GetValue(tc, null));//用pi.GetValue获得值
string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
//获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
if(value1.GetType() == typeof(int))
{
//进行你想要的操作
}
}
public int Pid
{
get { return pid; }
set { pid = value; }
}
//****************
public void InitialProperty()//初始化设定
{
System.Reflection.PropertyInfo[] properties = this.GetType().GetProperties();
foreach(var v in properties)
{
string type= v.PropertyType.Name;
if (type=="String")
{
v.SetValue(this,"456",null);
}
else if(type=="Bitmap")
{
v.SetValue(this, new Bitmap(Image.FromFile("1.png")), null);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)