如何向一个泛型函数传递实现了特定接口的类类型?

3
我想创建一个通用函数,签名类似于: void funcName<T>() ,其中T需要是我想要的某个特定接口的实现。如何进行这样的检查?如何将实现特定接口的类类型传递给通用函数?
因此,我创建了一些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

我该怎么做才能让我的函数接收的类类型不仅符合我所需的接口,而且还具有构造函数?
4个回答

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);

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接