将泛型类转换为父 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

为什么我不能转换ChildClassParentGenericClass<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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章