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

ibi*_*iza 12 c# interface class

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

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器抱怨..?

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>'.
Run Code Online (Sandbox Code Playgroud)

据我所知,接口说IEnumerable,类使用List,但List IEnumerable .....

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

Dai*_*Dai 12

这是类型协方差/逆变问题(参见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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,integersTitleCased应符合.NET的指导原则.

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


小智 5

尽管 List 实现了 IEnumerable 这不是接口的工作方式。该接口准确指定了需要为属性公开哪些类型。如果您创建了一个通用接口,例如

public interface IFoo<T> where T : IEnumerable<int>
{
    T integers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用IFoo<List<int>>它以您期望的方式实现它。