实现一个接口时,为什么我不能使用兼容的具体类型 [英] Why can't I use a compatible concrete type when implementing an interface
问题描述
我希望能够做这样的事:
I would like to be able to do something like this :
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; }
}
}
为什么编译器抱怨..?
Why does the compiler complains..?
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和类使用一个List,而是一个目录的是的一个IEnumerable .....
I understand that the interface says IEnumerable and the class uses a List, but a List is an IEnumerable.....
我该怎么办?我不想指定类IEnumerable的,我想用实现IEnumerable,就像一个列出具体类型...
what can I do? I do not want to specify IEnumerable in the class, I want to use a concrete type that implements IEnumerable, like List...
谢谢!
推荐答案
这是一个类型的协方差/逆变问题(见的 http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#C.23 )。
This is a Type Covariance/Contravariance issue (see http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#C.23 ).
有一个变通方法:使用显式接口,就像这样:
There's a workaround: use explicit interfaces, like so:
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的指引
Note that integers
should be TitleCased to conform to .NET's guidelines.
希望你可以看到在上面的代码中的问题:的IList< INT>
与的IEnumerable LT兼容&;&INT GT;
仅用于存取,而不是设置。 IEnumerable的< INT> :; INT>()(其中 Qux如果有人致电
IFoo.integers =新Qux<,会发生什么但不可以
Qux:IList的< INT>
)
Hopefully you can see the problem in the code above: IList<int>
is compatible with IEnumerable<int>
only for the accessor, but not for setting. What happens if someone calls IFoo.integers = new Qux<int>()
(where Qux : IEnumerable<int>
but not Qux : IList<int>
).
这篇关于实现一个接口时,为什么我不能使用兼容的具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!