这是C#泛型错误吗?

Fru*_*gle 3 .net c# generics interface

此代码产生以下错误:

错误1'ConsoleApplication1.FooBar'未实现接口成员'ConsoleApplication1.IFoo.Bar'.'ConsoleApplication1.FooBar.Bar'无法实现'ConsoleApplication1.IFoo.Bar',因为它没有匹配的返回类型'ConsoleApplication1.IBar'.

interface IBar
{

}

interface IFoo
{
    IBar Bar { get; }
}

class FooBar<T> : IFoo where T : IBar
{
    public T Bar
    {
        get { return null; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这不应该因为FooBar类中的where关键字而发生.

我使用Visual Studio 2013和.NET 4.5.1构建了它.

Lee*_*Lee 15

这不是一个错误 - Bar属性的返回类型应该完全匹配,即IBar.C#不支持返回类型协方差.

您可以显式实现该接口:

class FooBar<T> : IFoo where T : IBar
{
    public T Bar
    {
        get { return null; }
    }

    IFoo.Bar { get { return this.Bar; } }
}
Run Code Online (Sandbox Code Playgroud)