简体   繁体   English

如何传递给实现certan接口的泛型函数类类型?

[英]How to pass to a generic function class type that implements certan interface?

I want to create a generic function with signature like this : void funcName<T>() where T would be required to be an implementation of some particular interface I want. 我想创建一个带有签名的泛型函数,如下所示: void funcName<T>()其中T需要是我想要的某个特定接口的实现。 How to make such check? 怎么做这样的检查? How to pass to a generic function class type that implements certan interface? 如何传递给实现certan接口的泛型函数类类型?

So I create some public interface IofMine {} and I try to create a function like public static void funcName<T>() where T : IofMine { var a = new T} and sadly I get: 所以我创建了一些public interface IofMine {} ,我尝试创建一个像public static void funcName<T>() where T : IofMine { var a = new T}这样的函数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 错误:无法创建变量类型“T”的实例,因为它没有new()约束

What shall I do to make class types my function receives not only be of my desired interface but also have a constructor? 我该怎样做才能使我的函数接收类型不仅是我想要的接口而且还有一个构造函数?

In order to require that the generic parameter have a default constructor, specify new() as part of the generic constraint. 为了要求泛型参数具有默认构造函数,请将new()指定为泛型约束的一部分。

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

You can only use this to require a default (ie, no parameters) constructor. 您只能使用它来要求默认(即无参数)构造函数。 You can't require a constructor taking a string parameter, for example. 例如,您不能要求构造函数采用字符串参数。

Simple: 简单:

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

This creates a constraint on the type parameter T so that any type used when calling the method must implement IMyInterface . 这会在类型参数T上创建约束,以便在调用方法时使用的任何类型都必须实现IMyInterface

This is how you declare it: 这是你如何声明它:

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

This is how you call it: 这就是你怎么称呼它:

IMyInterface inst = new MyImplOfMyInterface();
funcName(inst);

If I understood you correct, you need to use constraints of generic: 如果我理解你是正确的,你需要使用泛型的约束:

public interface TestInterface
{
}

public void func<T>()
    where T : TestInterface
{ 

}

http://msdn.microsoft.com/en-us/library/d5x73970.aspx http://msdn.microsoft.com/en-us/library/d5x73970.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM