通用约束和接口实现/继承

Mat*_*ton 13 c# generics

不完全确定如何表达这个问题,因为它是"为什么这不起作用?" 查询类型.

我已将我的特定问题减少到此代码:

public interface IFoo
{
}

public class Foo : IFoo
{
}

public class Bar<T> where T : IFoo
{
    public Bar(T t)
    {
    }

    public Bar()
        : this(new Foo()) // cannot convert from 'Foo' to 'T'
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,通用类型TBar<T>必须实现IFoo的.那么为什么编译器会在评论中给出错误?当然,Foo的一个实例是IFoo,因此可以作为泛型类型的代表传递T

这是编译器限制还是我遗漏了什么?

And*_*nan 13

您还可以使用Fiz以任何其他方式实现与Foo无关的IFoo:

public interface IFoo
{
}

public class Foo : IFoo
{
}

public class Fiz : IFoo
{
}

Foo foo = new Foo();
Fiz fiz = foo; // Not gonna compile.
Run Code Online (Sandbox Code Playgroud)

你想要的可能更像是:

public class Bar<T> where T : IFoo, new()
{
    public Bar(T t)
    {
    }

    public Bar()
        : this(new T()) 
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以拥有

Bar<Foo> barFoo = new Bar<Foo>();
Bar<Fiz> barFiz = new Bar<Fiz>();
Run Code Online (Sandbox Code Playgroud)