这是C#泛型错误吗?

这是C#泛型错误吗?,c#,.net,generics,interface,C#,.net,Generics,Interface,此代码不正确,会产生以下错误: 错误1“ConsoleApplication1.FooBar”未实现接口成员“ConsoleApplication1.IFoo.Bar”ConsoleApplication1.FooBar.Bar“无法实现”ConsoleApplication1.IFoo.Bar“,因为它没有匹配的返回类型“ConsoleApplication1.IBar” 接口IBar { } 接口IFoo { IBar条{get;} } 类FooBar:IFoo其中T:IBar { 公共酒吧

此代码不正确,会产生以下错误:

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

接口IBar
{
}
接口IFoo
{
IBar条{get;}
}
类FooBar:IFoo其中T:IBar
{
公共酒吧
{
获取{return null;}
}
}
这不应该发生,因为FooBar类中有where关键字


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

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

您可以显式实现接口:

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

    IFoo.Bar { get { return this.Bar; } }
}
类FooBar:IFoo其中T:IBar
{
公共酒吧
{
获取{return null;}
}
IFoo.Bar{get{返回此.Bar;}}
}

这不是一个bug。由于接口定义不匹配,编译器无法实现它。一种可行的方法是使
IFoo
也具有通用性,如下所示:

interface IBar
{
}

interface IFoo<T>
{
    T Bar { get; }
}

class FooBar<T> : IFoo<T> where T : IBar
{
    public T Bar
    {
        get { return default(T); }
    }
}
接口IBar
{
}
接口IFoo
{
T条{get;}
}
类FooBar:IFoo其中T:IBar
{
公共酒吧
{
获取{返回默认值(T);}
}
}

在120%的情况下,我问自己“这是一个编译器/库错误吗?”,答案是“不是”。我已经做了25年了。曾经(我)有一个bug可以追溯到编译器问题(其中重命名变量解决了它,一个古老的C++编译器不知怎么把它搞砸了)。这可能是成千上万个bug中的一个。一般来说,你应该记住,编译器比几乎任何人的大脑都知道如何编译代码。错误几乎总是在大脑中,而不是编译器。
interface IBar
{
}

interface IFoo<T>
{
    T Bar { get; }
}

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