2013-01-15 173 views
0

我有一個泛型類,我想在其中保存一個使用類型T作爲參數和返回值的委託。我如何將方法分配給屬性getValueDefault?將函數賦值給通用委託

private delegate TOut GetValueDefault<in TIn, TOut>(string key, TIn defaultValue); 

private GetValueDefault<T, T> getValueDefault = null; 

例如帶有簽名的方法bool ThirdPartyClass.foo(string key, bool defValue)

+0

什麼是在這種情況下作爲'T'傳遞的泛型參數?除非它是'object',否則我認爲這是不可能的,因爲'string'和'bool'與其他類型不兼容。 – cdhowie

回答

1

它應該是那麼容易,因爲:

private delegate TOut GetValueDefault<in TIn, TOut>(string key, TIn defaultValue); 

private GetValueDefault<int, bool> getValueDefault = afoo; 

static bool ThirdPartyClass.foo(string key, int defValue) 
{ 
    \\... 
} 

然而,如果在所有情況下,你將擁有平等的進出類型參數,您可以將其簡化爲:

private delegate T GetValueDefault<T>(string key, T defaultValue); 

private static GetValueDefault<bool> getValueDefault = afoo; 
+0

這隻適用於'bool',如果'T'是別的,我想在構造函數中分配'(int)ThirdPartyClass.foo2(string key,int defaultValue)'。 – whatever0010011

+0

@MatthiasSchl我已經更新了我的答案,因爲它可以處理類型爲int的輸入參數 – horgh

0

我認爲你應該這樣寫:

class Sample<T> 
{ 
    public delegate TOut GetValueDefault<in TIn, TOut>(string key, TIn defaultValue); 

    private GetValueDefault<T, T> getValueDefault = null; 
    public Sample(GetValueDefault<T, T> del) 
    { 
     getValueDefault = del; 
    } 
}