简体   繁体   中英

Use interface as generic type with new constraint

In C#, I've define an Interface like following:

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 ? 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. Interface can't have constructors. Remove where T: new() constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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