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

我想要做这样的事情:
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>'.

我明白界面说IEnumerable和类使用一个列表,但一个列表是一个IEnumerable …..

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

谢谢!

解决方法

这是一个类型协方差/反差问题(见 http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#C.23).

一个解决方法:使用显式接口,像这样:

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; }
    }
}

请注意,整数应为TitleCased,以符合.NET的指导原则.

希望您可以在上面的代码中看到问题:IList< int>与IEnumerable< int>兼容只为访问者,而不是设置.如果有人打电话给IFoo.integers = new Qux< int>()(其中Qux:IEnumerable< int>但不是Qux:IList< int>))会发生什么.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...