c# - 这是 C# 泛型错误吗?

标签 c# .net generics interface

此代码会产生以下错误:

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# 不支持返回类型协变。

您可以显式实现接口(interface):

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

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

关于c# - 这是 C# 泛型错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424063/

相关文章:

c# - 使用 C# 从 SQL 显示和保存 "time"数据类型?

java - Collections.max() 签名的实际使用

java - 在 toString 方法中将对象转换为特定数据类型

java - 如何在 CDI 生成器中检索通用参数的类?

c# - EditItemTemplate 中 AJAX CascadingDropDown 和 DropDownList SelectedValue 的问题

c# - 用于远程 Web 服务的 Windows 虚拟磁盘

c# - 快速整数平方根

c# - 使用 BasicHttpBinding 进行 WCF 自定义证书验证

c# - 如何为闭源类型的所有属性注入(inject)自定义 UITypeEditor?

c# - LINQ 搜索/匹配