使用反射的名字在一个类实例获得一个属性的值 [英] Use reflection to get the value of a property by name in a class instance
本文介绍了使用反射的名字在一个类实例获得一个属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以说我有
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.
像下面的伪code:
public object GetVal(string propName)
{
return <propName>.value;
}
我怎样才能做到这一点使用反射?
How can I do this using reflection?
我使用asp.net 3.5编码,C#3.5
I am coding using 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);
这篇关于使用反射的名字在一个类实例获得一个属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文