简体   繁体   English

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

[英]Use reflection to get the value of a property by name in a class instance

Lets say I have 可以说我有

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

and I would like to create a method that accepts a string that contains either "age" or "name" and returns an object with the value of that property. 我想创建一个接受包含“age”或“name”的字符串的方法,并返回一个具有该属性值的对象。

Like the following pseudo code: 像下面的伪代码:

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

How can I do this using reflection? 我怎么能用反射做到这一点?

I am coding using asp.net 3.5, c# 3.5 我使用asp.net 3.5编译,c#3.5

I think this is the proper syntax... 我认为这是正确的语法......

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

First of all, the example you provided has no Properties. 首先,您提供的示例没有属性。 It has private member variables. 它有私有成员变量。 For properties, you would have something like: 对于属性,你会有类似的东西:

 
 
 
 
  
  
  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; } }
 
 
  

And then using reflection to get the values: 然后使用反射来获取值:

 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);
 }

Keep in mind, though, that since you would already have access to the class and its properties (because you also have access to the method), it's much easier just to use the properties rather than do something fancy via Reflection. 但请记住,既然您已经可以访问类及其属性(因为您也可以访问该方法),那么只使用属性而不是通过Reflection做一些奇特的事情会容易得多。

You can do something like this: 你可以这样做:

Person p = new Person( 10, "test" );

IEnumerable<FieldInfo> 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 );

Keep in mind since these are private instance fields you need to explicitly state the binding flags in order to get them via reflection. 请记住,因为这些是私有实例字段,您需要显式声明绑定标志,以便通过反射获取它们。

Edit: 编辑:

It seems you changed your sample from using fields to properties, so I'm just going to leave this here in case you change back again. 您似乎已将示例从使用字段更改为属性,因此我只是将其留在此处以防您再次更改。 :) :)

ClassInstance.GetType.GetProperties() will get you your list of PropertyInfo objects. ClassInstance.GetType.GetProperties()将为您提供PropertyInfo对象列表。 Spin through the PropertyInfos checking PropertyInfo.Name against propName. 旋转PropertyInfos,检查PropertyInfo.Name对propName。 If they're equal then call the GetValue method of the PropertyInfo class to get its value. 如果它们相等,则调用PropertyInfo类的GetValue方法以获取其值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM