使用反射在类实例中按名称获取属性的值
本文关键字:获取 属性 反射 实例 | 更新日期: 2023-09-27 17:59:44
假设我有
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);
首先,您提供的示例没有Properties。它具有私有成员变量。对于房产,你会有这样的东西:
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);
}
不过,请记住,由于您已经可以访问类及其属性(因为您也可以访问该方法),因此只使用这些属性比通过反射做一些花哨的事情要容易得多。
您可以这样做:
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,检查PropertyInfo.Name与propName。如果它们相等,则调用PropertyInfo类的GetValue方法以获取其值。
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx