将泛型类强制转换为父C#
我的问题可能又老又笨,但请帮帮我 这是我的密码:将泛型类强制转换为父C#,c#,generics,C#,Generics,我的问题可能又老又笨,但请帮帮我 这是我的密码: public class Program { public static void Main(string[] args) { var first = new ChildClass(); var result = new List<ParentGenericClass<ITypeInterface>>(); result.Add(first); }
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> { }
公共类程序
{
公共静态void Main(字符串[]args)
{
var first=新的子类();
var result=新列表();
结果。添加(第一);
}
}
公共接口ITypeInterface{}
公共类TypeClass:ITypeInterface{}
公共类ParentGenericClass,其中ToObject:ITypeInterface{}
公共类子类:ParentGenericClass{}
TypeClass
是ITypeInterface
的子类,ChildClass
是ParentGenericClass
的子类
为什么我不能将ChildClass
转换为ParentGenericClass
?
我认为它应该很好用
我错过了什么
我用generic
、cast
等关键词进行了搜索,但没有找到好的答案 这是一个差异问题,仅在接口上支持使用covarientout
,而在类上不支持
协方差使您能够使用比最初指定的更派生的类型
事实是,ChildClass
实际上与ParentGenericClass
一种选择是重构成这样的东西
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);
公共接口IParentGenericClass,其中ToObject:ITypeInterface
{
}
公共类ParentGenericClass:IParentGenericClass
where-TObject:ITypeInterface
{
}
...
var result=新列表();
结果。添加(第一);