2016-05-17 29 views
3

這是我需要做的簡化版本。在目前的狀態下,我試圖做的事情沒有意義。但它以簡單的方式顯示了問題。試圖呼叫功能<T>其中T:TheClass,new()在其中T:class

我需要調用一個函數2 < T>()其中,T:theClass描述,新的()一個功能1 < T內部>()其中,T:類

Something<T> function1<T>() where T : class { 
    //cannot call function2 directly due to compile error 
    //return function2<T>(); 

    //What I need as a pseudo code 
    if (T is TheClass and T is new()) 
    return Then function2<T>() 
    else 
    throw Exception 
} 

Something<T> function2<T>() where T : TheClass, new() { 
    //... 
} 
+14

如果輸入的是無效的 - 爲什麼不對函數1應用相同的限制(TheClass,new())? – Evk

+0

你試圖直接調用function2和什麼類型的T是什麼編譯器錯誤? –

+0

@MarcoFatica無關緊要的是'T'由於'function1'上的約束並不強制它有一個默認的構造函數,所以它不能用在'function2'的參數上。 –

回答

2

new()限制可以」 t在運行時進行驗證(不像繼承可以使用as/is) - 所以沒有C#構造可以編寫來調用function2function1並保持強類型。

你唯一的選擇是通過反射構建方法,而不是稱之爲。見How do I use reflection to call a generic method?

0

你真的不能這樣做。我猜function2在某些情況下做new T(),這可能只是T : class約束在function1

你可以嘗試例如去除new()約束和做手工用支票對ConstructorInfo,並從中獲得一個實例還有:既然你拋出異常反正

Type type = typeof(T); 
    ConstructorInfo ctor = type.GetConstructor(new Type[0]); 
    if(ctor == null) throw new InvalidOperationException(); 
    object instance = ctor.Invoke(new object[0]);