2011-08-30 16 views
3

在.NET 2.0(與C#3.0),我怎麼能創建一個屬性訪問器通過反射獲得委託,當我不知道它的類型在編譯時?當財產類型未知時,通過反射獲得屬性的代理創建委託

例如如果我有int類型的財產,我可以這樣做:

Func<int> getter = (Func<int>)Delegate.CreateDelegate(
    typeof(Func<int>), 
    this, property.GetGetMethod(true)); 
Action<int> setter = (Action<int>)Delegate.CreateDelegate(
    typeof(Action<int>), 
    this, property.GetSetMethod(true)); 

,但如果我不知道物業是在編譯時什麼類型的,我不知道該怎麼做。

+1

不知道,但這下面的問題看起來有關:http://stackoverflow.com/questions/773099/generating-delegate-types-dynamically-in-c – Till

+0

'功能'是.NET 3.5 ....是這是一個自定義的'Func '? –

+0

@Marc Gravell - Whoops實際上是在一個針對錯誤平臺的臨時項目中玩耍,但它可以在.NET 2.0中使用自定義的Func 。 – Ergwun

回答

2

你需要的是:

Delegate getter = Delegate.CreateDelegate(
    typeof(Func<>).MakeGenericType(property.PropertyType), this, 
    property.GetGetMethod(true)); 
Delegate setter = Delegate.CreateDelegate(
    typeof(Action<>).MakeGenericType(property.PropertyType), this, 
    property.GetSetMethod(true)); 

但是,如果你這樣做是對的表現,你還是要來了短,因爲你需要使用DynamicInvoke(),這是slooow。您可能希望查看元編程來編寫一個包含/返回object的包裝。或者看看HyperDescriptor是否爲你做到這一點。

+0

關於http://stackoverflow.com/questions/2490828/createdelegate-with-unknown-types? – Till

+0

@Till如果你的意思是接受的答案......如果你事先不知道類型,你將不得不使用'MakeGenericMethod()';然後它使用反射創建一個委託立即使用一次並放棄。坦率地說,在那個例子中,原始反射('GetValue()'/'SetValue()')會更好。 –

+0

@馬克礫石 - 是的,正在努力做到這一點。當我有更多時間時,我會查看HyperDescriptor - 看起來很棒。 – Ergwun

相關問題