c# – 为什么在实现接口时不能使用兼容的具体类型
发布时间:2020-12-15 06:41:25 所属栏目:百科 来源:网络整理
导读:我想要做这样的事情: using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test{ public interface IFoo { IEnumerableint integers { get; set; } } public class Bar : IFoo { public Listint integers { get;
我想要做这样的事情:
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>))会发生什么. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |