2011-02-02 58 views
0

假設我有一些通用的interface IMyInterface<TParameter1, TParameter2>C#通用參數

現在,如果我正在寫另一個類,一般在它的參數T

CustomClass<T> where T : IMyInterface

應該如何進行?

(當前代碼不能編譯,因爲IMyInterface取決於TParameter, TParameter2


我認爲它應該像做:

CustomClass<T, TParameter1, TParameter2> where T: IMyInterface<TParameter1, 
                   TParameter2> 

,但我可能是錯的,你能指點我好嗎?

+0

你的假設是正確的。 – 2011-02-02 21:01:10

回答

4

這正是因爲你擁有它,你需要在要求上IMyInterface通用約束類指定TParameter1TParameter2通用參數:

public interface IMyInterface<TParameter1, TParameter2> 
{ 
} 

public class CustomClass<T, TParameter1, TParameter2> 
    where T : IMyInterface<TParameter1, TParameter2> 
{ 

} 

,或者你可以讓他們固定的:

public class CustomClass<T> 
    where T : IMyInterface<string, int> 
{ 

} 
0

你真的想用它作爲約束嗎?(用'where'關鍵字)?以下是直實施的一些例子:

interface ITwoTypes<T1, T2> 

class TwoTypes<T1, T2> : ITwoTypes<T1, T2> 

或者,如果你知道類型的類會使用,你不需要在類的類型參數:

class StringAndIntClass : ITwoTypes<int, string> 

class StringAndSomething<T> : ITwoTypes<string, T> 

如果你正在使用接口作爲約束,並不知道顯式指定的類型,那麼你需要將類型參數添加到類聲明中,正如你所想的那樣。

class SomethingAndSomethingElse<T, TSomething, TSomethingElse> where T : ITwoTypes<TSomething, TSomethingElse> 

class StringAndSomething<T, TSomething> where T : ITwoTypes<string, TSomething>