使用Jon Skeet的文章Making reflection fly and exploring delegates作爲指南,我試圖使用Delegate.CreateDelegate方法作爲代理重複屬性。下面是一個例子類:C#使用具有值類型的屬性與Delegate.CreateDelegate
public class PropertyGetter
{
public int Prop1 {get;set;}
public string Prop2 {get;set;}
public object GetPropValue(string propertyName)
{
var property = GetType().GetProperty(propertyName).GetGetMethod();
propertyDelegate = (Func<object>)Delegate.CreateDelegate(typeof(Func<object>), this, property);
return propertyDelegate();
}
}
我遇到的問題是,當我打電話GetPropValue
和"Prop1"
作爲參數傳遞,我得到在電話會議上的ArgumentException
到Delegate.CreateDelegate
與消息"Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
使用任何屬性時,會出現這種情況它返回一個包含結構體的基元/值類型。
有沒有人知道一種方法能夠在這裏使用引用和值類型?
你只是想要屬性的值,或者你真的想返回一個代表getter的委託嗎?如果前者只使用'PropertyInfo.GetValue'。 – Servy