[英]Child/Parent inheritance/casting and Generic type
如果我只是这样定义基类和继承类
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有效
有什么建议可以在这种情况下如何仍然使用基类来表示继承的类?
当然这是行不通的。
您的类AnotherInherited
继承自AnotherBase<AnotherInheritedDetail>
而不是AnotherBase<AnotherDetail>
。 这对您来说似乎很奇怪,但是您是在继承另一个类,而不是泛型。
您可以在处理对象时使用可互换的泛型,但是类定义仅声明这一继承。
至少那是我的理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.