c# – 为什么列表在协变界面MyInterface上无效
发布时间:2020-12-15 06:39:00 所属栏目:百科 来源:网络整理
导读:跟进问题到 a previous question,这被确定为共同问题.进一步,如果我修改IFactory如下: class Program{ static void Main(string[] args) { IFactoryIProduct factory = new Factory(); }}class Factory : IFactoryProduct{}class Product : IProduct{}inter
跟进问题到
a previous question,这被确定为共同问题.进一步,如果我修改IFactory如下:
class Program { static void Main(string[] args) { IFactory<IProduct> factory = new Factory(); } } class Factory : IFactory<Product> { } class Product : IProduct { } interface IFactory<out T> where T : IProduct { List<T> MakeStuff(); } interface IProduct { } 我得到:
为什么这不一定有效?如何解决? 解决方法
@Craig’s answer是正确的.要解决,请将其更改为:
IEnumerable<T> MakeStuff() 编辑:至于为什么,看看IEnumerable<T> Interface的定义: public interface IEnumerable<out T> : IEnumerable 请注意,IList<T> Interface没有out关键字.对于接口和委托,而不是类,通用类型参数支持差异,因此它不适用于List< T>. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |