子/父继承/转换和通用类型

时间:2017-07-05 15:21:58

标签: c# inheritance

如果我只是这样定义基类和继承类

abstract class Base
{
}

class Inherited : Base
{
}

我可以毫无错误地使用Base a = new Inherited();

但是如果我有复杂的泛型基类,例如,请参阅下面的代码:

abstract class AnotherBase<TDetailType> where TDetailType : AnotherDetail
{
    public List<TDetailType> Children { get; set; }
}

abstract class AnotherDetail
{
}

我继承了课程

class AnotherInherited : AnotherBase<AnotherInheritedDetail>
{
}

class AnotherInheritedDetail : AnotherDetail
{
}

显然我不能再使用类似的语法AnotherBase<AnotherDetail> b = new AnotherInherited();因为编译器提供了错误信息

  

严重级代码描述项目文件行抑制状态   错误CS0029无法隐式转换类型   'ConsoleApplication3.AnotherInherited'到   'ConsoleApplication3.AnotherBase'ConsoleApplication3 c:\ temp \ ConsoleApplication3 \ ConsoleApplication3 \ Program.cs 15 Active

任何建议如何在这种情况下仍然使用基类来表示继承的类?

1 个答案:

答案 0 :(得分:1)

当然这不起作用。

您的班级AnotherInherited继承自AnotherBase<AnotherInheritedDetail>而非AnotherBase<AnotherDetail>。这对你来说可能看起来很奇怪,但是你继承了另一个类,而不是泛型。

您可以在处理对象时使用泛型可互换,但类定义仅声明这一个继承。

至少这是我的理解。