且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中使用反射从字符串获取属性值

更新时间:2023-11-02 20:03:04

 公共静态对象GetPropValue(SRC对象,字符串作为propName)
 {
     返回src.GetType()的getProperty(作为propName).GetValue(SRC,NULL);
 }

当然,你将要添加验证和诸如此类的东西,但这是它的精神。

I am trying implement the Data transformation using Reflection1 example in my code.

The GetSourceValue function has a switch comparing various types, but I want to remove these types and properties and have GetSourceValue get the value of the property using only a single string as the parameter. I want to pass a class and property in the string and resolve the value of the property.

Is this possible?

1Web Archive version of original blog post

 public static object GetPropValue(object src, string propName)
 {
     return src.GetType().GetProperty(propName).GetValue(src, null);
 }

Of course, you will want to add validation and whatnot, but that is the gist of it.