2013-10-08 60 views
2

使用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"作爲參數傳遞,我得到在電話會議上的ArgumentExceptionDelegate.CreateDelegate與消息"Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."使用任何屬性時,會出現這種情況它返回一個包含結構體的基元/值類型。

有沒有人知道一種方法能夠在這裏使用引用和值類型?

+0

你只是想要屬性的值,或者你真的想返回一個代表getter的委託嗎?如果前者只使用'PropertyInfo.GetValue'。 – Servy

回答

3

從根本上說,您的一般方法是不可能的。您能夠採取所有非價值類型並將其視爲Func<object>的原因是依靠逆變(Func<T>T相抵觸)。根據語言規範,逆變不支持值類型。

當然,如果你不依賴這種方法,問題會變得更加容易。

如果你只是想獲得的價值使用PropertyInfo.GetValue方法:

public object GetPropValue(string name) 
{ 
    return GetType().GetProperty(name).GetValue(this); 
} 

如果你想返回一個Func<object>,將獲取每當它就是所謂的價值,只是圍繞該反射調用拉姆達:

public Func<object> GetPropValue2(string name) 
{ 
    return() => GetType().GetProperty(name).GetValue(this); 
} 
+0

我得到了所有複製Jon的性能增強,甚至沒有想到使用PropertyInfo.GetValue。有趣的是,我測試了GetValue的性能,我在問題中提到的方法,以及使用Stopwatch直接訪問屬性,並發現GetValue比我在問題中使用的方法更快。謝謝。 –

相關問題