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

问题描述

|| 可以说我有
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 <propName>.value;  
    }
如何使用反射来做到这一点? 我正在使用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;
    }
}
然后使用反射来获取值:
 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<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 );
请记住,由于这些是私有实例字段,因此您需要显式声明绑定标志,以便通过反射获取它们。 编辑: 似乎您已将示例从使用字段更改为属性,因此,如果您再次更改,我将在此处保留此示例。 :)     ,        ClassInstance.GetType.GetProperties()将获取您的PropertyInfo对象列表。 遍历PropertyInfos,对照propName检查PropertyInfo.Name。如果它们相等,则调用PropertyInfo类的GetValue方法以获取其值。 http://msdn.microsoft.com/zh-CN/library/system.reflection.propertyinfo.aspx     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...