2012-07-23 66 views
3

我想创建一个像这样的签名的通用函数:void funcName<T>()其中T将被要求是我想要的某个特定接口的实现。如何做这样的检查?如何传递给实现certan接口的通用函数类类型?如何传递给实现certan接口的通用函数类类型?

所以我创造一些public interface IofMine {},我尝试创建一个功能类似public static void funcName<T>() where T : IofMine { var a = new T}和可悲的是,我得到:

Error: Cannot create an instance of the variable type 'T' because it does not have the new() constraint

我该怎么做才能让类的类型我的功能不仅接收是我想要的界面,而且还有一个构造函数?

回答

5

为了要求通用参数具有默认构造函数,请指定new()作为通用约束的一部分。

public static void funcName<T>() where T : IofMine, new() 
{ 
    T a = new T(); 
} 

您只能使用这需要一个默认的(即无参数)构造函数。例如,您不能要求构造函数接受字符串参数。

2

简单:

public void FuncName<T>(...) 
    where T : IMyInterface 
{ 
    ... 
} 

这将创建的类型参数T的约束,这样在调用方法时所使用的任何类型必须实现IMyInterface

2

这是你如何把它声明:

// Let's say that your function takes 
// an instance of IMyInterface as a parameter: 
void funcName<T>(T instance) where T : IMyInterface { 
    instance.SomeInterfaceMethodFromMyInterface(); 
} 

这是你如何称呼它:

IMyInterface inst = new MyImplOfMyInterface(); 
funcName(inst); 
相关问题