[英]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}
}
我想創建一個接受包含“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,檢查PropertyInfo.Name對propName。 如果它們相等,則調用PropertyInfo類的GetValue方法以獲取其值。
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.