加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

这是C#泛型错误吗?

发布时间:2020-12-15 19:39:03 所属栏目:百科 来源:网络整理
导读:此代码产生以下错误: Error 1 ‘ConsoleApplication1.FooBar’ does not implement interface member ‘ConsoleApplication1.IFoo.Bar’. ‘ConsoleApplication1.FooBar.Bar’ cannot implement ‘ConsoleApplication1.IFoo.Bar’ because it does not have
此代码产生以下错误:

Error 1 ‘ConsoleApplication1.FooBar’ does not implement interface member ‘ConsoleApplication1.IFoo.Bar’. ‘ConsoleApplication1.FooBar.Bar’ cannot implement ‘ConsoleApplication1.IFoo.Bar’ because it does not have the matching return type of ‘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构建了它.

解决方法

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

您可以显式实现该接口:

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

    IFoo.Bar { get { return this.Bar; } }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读