2013-12-21 37 views
3

我想用Func < T,bool >來包裝一個lambda Func <bool>其中T僅在運行時已知。我並不希望實際發出的代碼對該參數執行任何操作,它只會被忽略,並且會調用包裝的方法。在運行時(不是編譯時)使用具有不同簽名的委託來包裝委託

舉例來說,如果我有:

Func<bool> innerFunc =() => true 

在運行時,我需要做這樣的事情:

Type paramType = typeof (String); // or any other Type 
Type wrappedFuncType = typeof (Func<,>).MakeGenericType (paramType, typeof (bool)) 
// this next line is close to what I want to do but isn't correct 
Delegate wrappedFunc = Delegate.CreateDelegate (wrappedFuncType, this, innerFunc.Method); 

我見過使用LambdaExpression.Compile這有可能工作的一些代碼,但因爲此代碼位於PCL中,面向.NET 4.5,SL4 +,WP7 +,WinStore,因此它看起來並不可用。

TL; DR

如何包裹Func鍵<布爾>委託以便它匹配像Func鍵<字符串,布爾>和調用外部委託返回從內部代表的價值?

UPDATE 感謝@usr,我得到它的工作是這樣的:

private static Func<T, bool> WrapFuncBool<T> (Func<bool> func) 
{ 
    return _ => func(); 
} 

private Delegate CreateParameterizedFuncBoolDelegate (Type parameterType) 
{ 
    var wrapMethodInfo = this.GetType().GetMethod ("WrapFuncBool", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod (parameterType); 
    return (Delegate) wrapMethodInfo.Invoke (this, new object[] { (Func<bool>) (() => true) }); 
} 

回答

2

寫的包裝在C#:

static Func<T, bool> Wrap<T>(Func<bool> f) { 
return _ => f(); 
} 

現在叫Wrap使用反射(MakeGenericMethod)。

+0

啊我想我明白了 - 動態地調用一個調用Wrap並將Type作爲一個通用參數傳遞......我會試試這個! – PhilChuang