我希望能够做这样的事情:
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/