Bra*_*don 6 c# virtual inheritance abstract
我试图在子类中使用虚方法覆盖抽象类中的抽象方法.我(假设到现在?)了解抽象方法和虚方法之间的区别.
显然我无法做到,但我的问题是......为什么?基于此处接受的答案和以下场景,我只是没有看到问题:
public abstract class TopLevelParent
{
protected abstract void TheAbstractMethod();
}
public class FirstLevelChild1 : TopLevelParent
{
protected override void TheAbstractMethod()
{
}
}
public class FirstLevelChild2 : TopLevelParent
{
protected virtual override void TheAbstractMethod()
{
//Do some stuff here
}
}
public class SecondLevelChild : FirstLevelChild2
{
//Don't need to re-implement the method here... my parent does it the way I need.
}
Run Code Online (Sandbox Code Playgroud)
所以,我所做的就是让一个顶级父级有两个继承子级,另一个继承自其中一个继承子级.同样,根据我在上面发布的链接中接受的答案:
"一个虚函数,基本上就是说看,这里的功能对于子类来说可能是也可能不够好.所以如果它足够好,使用这个方法,如果没有,那么覆盖我,并提供你自己的功能. "
并且第二级子级将从其父级继承虚拟方法,从而满足其最顶层父级的抽象方法的实现要求......问题是什么?
我错过了某些阻碍我对此理解的细节......
p.s*_*w.g 15
一种override
方法是(在这个意义上,它可以在一个子类被覆盖)隐式虚拟的,除非标记为sealed
.
注意:
public class FirstLevelChild1 : TopLevelParent
{
protected override void TheAbstractMethod() { }
}
public class SecondLevelChild1 : FirstLevelChild1
{
protected override void TheAbstractMethod() { } // No problem
}
public class FirstLevelChild2 : TopLevelParent
{
protected sealed override void TheAbstractMethod() { }
}
public class SecondLevelChild : FirstLevelChild2
{
protected override void TheAbstractMethod() { }
// Error: cannot override inherited member
// 'FirstLevelChild2.TheAbstractMethod()' because it is sealed
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1216 次 |
最近记录: |