泛型函数,泛型类型是任何接口

Gre*_*mil 3 c# generics interface

我想用通用约束实现泛型函数,传入的Type是一个接口.这可能在C#中吗?我没有约束它工作正常,但如果它不是一个接口,代码将在运行时失败,所以我想让编译时检查.

public T MyFunction<T> where T : {any interface type} { return null; }
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 7

您可以将类型约束到特定接口,但不能"任何"任意接口.

// This is allowable
public T MyFunction<T>() where T : IMyInterface { return null; }
Run Code Online (Sandbox Code Playgroud)

这将允许您传递实现该特定接口的任何对象.


编辑:

鉴于你的目标,从评论中,我个人可能只是进行一些运行时检查:

public IEnumerable<T> LoadInterfaceImplementations<T>()
{
    Type type = typeof(T);
    if (!type.IsInterface)
        throw new ArgumentException("The type must be an Interface");

    // ...
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*son 5

不,没有办法只将类型约束到接口.