2011-02-02 60 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>