C#通过属性名称获取(读取)属性值的方法
之前在开发一个程序,希望能够通过属性名称读取出属性值,但是由于那时候不熟悉反射,所以并没有找到合适的方法,做了不少的重复性工作啊!
然后今天我再上网找了找,被我找到了,跟大家分享一下。
其实原理并不复杂,就是通过反射利用属性名称去获取属性值,以前对反射不熟悉,所以没想到啊~
不得不说反射是一种很强大的技术。。
下面给代码,希望能帮到有需要的人。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespacePropertyNameGetPropertyValueDemo
{
classProgram
{
staticvoidMain(string[]args)
{
Personps=newPerson();
ps.Name="CTZ";
ps.Age=21;
Demodm=newDemo();
dm.Str="String";
dm.I=1;
Console.WriteLine(ps.GetValue("Name"));
Console.WriteLine(ps.GetValue("Age"));
Console.WriteLine(dm.GetValue("Str"));
Console.WriteLine(dm.GetValue("I"));
}
}
abstractclassAbstractGetValue
{
publicobjectGetValue(stringpropertyName)
{
returnthis.GetType().GetProperty(propertyName).GetValue(this,null);
}
}
classPerson:AbstractGetValue
{
publicstringName
{get;set;}
publicintAge
{get;set;}
}
classDemo:AbstractGetValue
{
publicstringStr
{get;set;}
publicintI
{get;set;}
}
}
如果觉得上面比较复杂了,可以看下面的简化版。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespaceGetValue
{
classProgram
{
staticvoidMain(string[]args)
{
Personps=newPerson();
ps.Name="CTZ";
ps.Age=21;
Console.WriteLine(ps.GetValue("Name"));
Console.WriteLine(ps.GetValue("Age"));
}
}
classPerson
{
publicstringName
{get;set;}
publicintAge
{get;set;}
publicobjectGetValue(stringpropertyName)
{
returnthis.GetType().GetProperty(propertyName).GetValue(this,null);
}
}
}
实质语句只有一句:
this.GetType().GetProperty(propertyName).GetValue(this,null);
其他可以忽略。。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!
