c# - 为什么在实现接口(interface)时不能使用兼容的具体类型

标签 c# class interface

我希望能够做这样的事情:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    public interface IFoo
    {
        IEnumerable<int> integers { get; set; }
    }

    public class Bar : IFoo
    {
        public List<int> integers { get; set; }
    }
}

为什么编译器会报错……?

Error   2   'Test.Bar' does not implement interface member 'Test.IFoo.integers'. 'Test.Bar.integers' cannot implement 'Test.IFoo.integers' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable<int>'.

我知道接口(interface)说 IEnumerable 并且类使用 List,但是 List IEnumerable.....

我能做什么?我不想在类中指定 IEnumerable,我想使用实现 IEnumerable 的具体类型,例如 List...

最佳答案

这是类型协变/逆变问题(参见 http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#C.23)。

有一个解决方法:使用显式接口(interface),如下所示:

public class Bar : IFoo {

    private IList<int> _integers;

    IEnumerable<int> IFoo.integers {
        get { return _integers };
        set { _integers = value as IList<int>; }
    }

    public IList<int> integers {
        get { return _integers; }
        set { _integers = vale; }
    }
}

请注意 integers应采用 TitleCased 以符合 .NET 的准则。

希望你能看到上面代码中的问题:IList<int>IEnumerable<int> 兼容仅适用于访问器(accessor),不适用于设置。如果有人调用 IFoo.integers = new Qux<int>() 会发生什么(其中 Qux : IEnumerable<int>不是 Qux : IList<int> )。

关于c# - 为什么在实现接口(interface)时不能使用兼容的具体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490633/

相关文章:

c# - 接口(interface)继承和new关键字

java - 说接口(interface)也是一种类型是什么意思?

c# - 为什么 JsonConvert 在反序列化为字典时抛出异常

c# - 数据库未更新

c# - 按另一个列表更新列表 (linq)

javascript - 超出最大调用堆栈大小 - 没有明显的递归

c# - 在不使用 .NET 序列化程序的情况下将 Hashtable 转换为 xml 字符串并返回到 HashTable

c# - 处理多个 List<Class> 的通用方法

java - java中的简单抽象类

c# - 在 C# 中实现接口(interface)与显式实现接口(interface)