简体   繁体   English

使用接口作为具有新约束的泛型类型

[英]Use interface as generic type with new constraint

In C#, I've define an Interface like following:在 C# 中,我定义了一个接口,如下所示:

public interface IClassA
{
    IEnumerable<T> Search<T>()
        where T : new();
}

and

public interface IClassB
{
    ...
}

If I do如果我做

public DoSomething(IClassA a)
{
    // Error: IClassB must be a non-abstract type with a public parameterless constructor.
    var result = a.Search<IClassB>();
}

How can I fix this so that I can pass IClassB as generic type in IClassA.Search ?我该如何解决这个问题,以便我可以在IClassA.Search 中将IClassB作为泛型类型传递 or this is impossible?或者这是不可能的?

You added constraint new() to your method, which means, that a type argument in a generic method declaration must have a public parameterless constructor.您在方法中添加了约束new() ,这意味着泛型方法声明中的类型参数必须具有公共无参数构造函数。 Interface can't have constructors.接口不能有构造函数。 Remove where T: new() constraint.删除where T: new()约束。

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

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