[英]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.