我們有一些代碼給出了屬性名稱使用反射來實現比較器。給定一個屬性名稱,我如何創建一個委託來獲得它的值
我想存儲委託/ Func來獲取價值,而不是每次我們需要獲得價值時支付反映價格。
鑑於一類是這樣的:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
我試着寫這將創建一個委託我
Func<T, object> CreateGetFuncFor<T>(string propertyName)
{
PropertyInfo prop = typeof(T).GetProperty(propertyName);
return (Func<T, object>)Delegate.CreateDelegate(typeof(Func<T, object>),
null,
prop.GetGetMethod());
}
功能下面的代碼工作正常,爲獲取名稱
var person = new Person { Name = "Dave", Age = 42 };
var funcitonToGetName = CreateGetFuncFor<Person>("Name");
Console.WriteLine(funcitonToGetName(person));
var functionToGetAge = CreateGetFuncFor<Person>("Age");
但對於Age proerty,它會拋出一個ArgumentException,並顯示消息「Error binding to targ et方法「
我錯過了什麼?還有另一種方法可以做到嗎?
感謝兩位盧克! – Argos 2010-10-21 16:23:41