[英]Casting a generic class to parent C#
我的问题可能古老而愚蠢,但请帮助我。
这是我的代码:
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
。
协方差使您可以使用比最初指定的类型更多的派生类型。
事实是, 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.