Csharp/C#教程: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);

其他可以忽略。。

您可能感兴趣的文章:C#正则表达式获取下拉菜单(select)的相关属性值C#通过XML节点属性/属性值读取写入XML操作代码实例C#读取XML中元素和属性值的实现代码

标签: 属性 属性值 方法

C#使用UdpClient类进行简单通信的实例

C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法

上述就是C#学习教程:C#通过属性名称获取(读取)属性值的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907627.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐