跟进问题到
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
- {
- }
我得到:
Invalid variance: The type parameter T must be invariantly valid on SandBox.IFactory.MakeStuff(). T is covariant.
为什么这不一定有效?如何解决?
解决方法
@Craig’s answer是正确的.要解决,请将其更改为:
- IEnumerable<T> MakeStuff()
编辑:至于为什么,看看IEnumerable<T> Interface的定义:
- public interface IEnumerable<out T> : IEnumerable
请注意,IList<T> Interface没有out关键字.对于接口和委托,而不是类,通用类型参数支持差异,因此它不适用于List< T>.