我的问题可能既老又愚蠢,但请帮助我。
这是我的代码:
public class Program
{
public static void Main(string[] args)
{
var first = new ChildClass();
var result = new List<ParentGenericClass<ITypeInterface>>();
result.Add(first);
}
}
public interface ITypeInterface { }
public class TypeClass : ITypeInterface { }
public class ParentGenericClass<TObject> where TObject : ITypeInterface { }
public class ChildClass : ParentGenericClass<TypeClass> { }
TypeClass
是 的孩子ITypeInterface
并且ChildClass
是 的孩子ParentGenericClass
。
为什么我不能转换ChildClass
为ParentGenericClass<ITypeInterface>
?我认为它应该可以正常工作。
我错过了什么?
我搜索了诸如generic
、 等关键字,cast
但找不到好的答案。
这是一个方差问题,协out
变的使用仅支持在接口而不是类上。
Covariance使您能够使用比最初指定的更派生的类型。
事实是,ChildClass
实际上并不等同于ParentGenericClass<ITypeInterface>
一种选择是重构为这样的东西
public interface IParentGenericClass<out TObject> where TObject : ITypeInterface
{
}
public class ParentGenericClass<TObject> : IParentGenericClass<TObject>
where TObject : ITypeInterface
{
}
...
var result = new List<IParentGenericClass<ITypeInterface>>();
result.Add(first);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句