使用reflection在类实例中按名称获取属性的值

可以说我有

class Person { public Person(int age, string name) { Age = age; Name = name; } public int Age{get;set} public string Name{get;set} } 

我想创建一个接受包含“age”或“name”的字符串的方法,并返回一个具有该属性值的对象。

像下面的伪代码:

  public object GetVal(string propName) { return .value; } 

我怎么能用reflection做到这一点?

我使用asp.net 3.5编译,c#3.5

我认为这是正确的语法……

 var myPropInfo = myType.GetProperty("MyProperty"); var myValue = myPropInfo.GetValue(myInstance, null); 

首先,您提供的示例没有属性。 它有私有成员变量。 对于属性,你会有类似的东西:

 public class Person { public int Age { get; private set; } public string Name { get; private set; } public Person(int age, string name) { Age = age; Name = name; } } 

然后使用reflection来获取值:

  public object GetVal(string propName) { var type = this.GetType(); var propInfo = type.GetProperty(propName, BindingFlags.Instance); if(propInfo == null) throw new ArgumentException(String.Format( "{0} is not a valid property of type: {1}", propName, type.FullName)); return propInfo.GetValue(this); } 

但请记住,由于您已经可以访问类及其属性(因为您也可以访问该方法),因此使用属性更容易,而不是通过Reflection做一些奇特的事情。

你可以这样做:

 Person p = new Person( 10, "test" ); IEnumerable fields = typeof( Person ).GetFields( BindingFlags.NonPublic | BindingFlags.Instance ); string name = ( string ) fields.Single( f => f.Name.Equals( "name" ) ).GetValue( p ); int age = ( int ) fields.Single( f => f.Name.Equals( "age" ) ).GetValue( p ); 

请记住,因为这些是私有实例字段,您需要显式声明绑定标志,以便通过reflection获取它们。

编辑:

您似乎已将示例从使用字段更改为属性,因此我只是将此保留在此处以防您再次更改。 🙂

ClassInstance.GetType.GetProperties()将为您提供PropertyInfo对象列表。 旋转PropertyInfos,检查PropertyInfo.Name对propName。 如果它们相等,则调用PropertyInfo类的GetValue方法以获取其值。

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx