这是c#泛型错误吗?

本文关键字:错误 泛型 这是 | 更新日期: 2023-09-27 17:50:20

这段代码会产生以下错误:

错误1 'ConsoleApplication1。FooBar'没有实现接口成员'ConsoleApplication1.IFoo.Bar'。"ConsoleApplication1.FooBar。栏'无法实现'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; }
    }
}

这应该不会发生,因为在FooBar类中的where关键字。

我是用Visual Studio 2013和。net 4.5.1构建的

这是c#泛型错误吗?

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

你可以显式地实现接口:

class FooBar<T> : IFoo where T : IBar
{
    public T Bar
    {
        get { return null; }
    }
    IFoo.Bar { get { return this.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); }
    }
}