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

The*_*oot 9 c# asp.net reflection

可以说我有

class Person
{
    public Person(int age, string name)
    {
        Age = age;
        Name = name; 
    }
    public int Age{get;set}
    public string Name{get;set}
}
Run Code Online (Sandbox Code Playgroud)

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

像下面的伪代码:

    public object GetVal(string propName)
    {
        return <propName>.value;  
    }
Run Code Online (Sandbox Code Playgroud)

我怎么能用反射做到这一点?

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

Tod*_*odd 14

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

var myPropInfo = myType.GetProperty("MyProperty");
var myValue = myPropInfo.GetValue(myInstance, null);
Run Code Online (Sandbox Code Playgroud)