问题描述
我有一个抽象基类:
抽象类Foo
{
虚拟无效DoSomeStuff( )
{
//做一些东西
}
抽象无效DoSomeCrazyStuff();
}
和从派生另外一个抽象类:
抽象类酒吧:富
{
抽象的覆盖无效DoSomeStuff();
抽象的覆盖无效DoSomeCrazyStuff();
}
我明白你为什么会想抽象覆盖 DoSomeStuff()
- 这将需要进一步派生类的新的实现。但我不明白,为什么你想抽象覆盖 DoSomeCrazyStuff()
。至于我可以告诉大家,它是多余的 - 我敢肯定,取出,将具有零负面影响。
是否存在这样一种抽象的抽象的覆盖做了一些用例一些有用的东西?如果没有,为什么没有一个编译器警告,通知我说什么,我已经写了什么都不做?
For starters, there's no practical reason for preventing it. If it produced a compiler error, all that would do is make classes more brittle. For example:
abstract class Foo
{
virtual void DoSomeStuff()
{
//Do Some Stuff
}
}
abstract class Bar : Foo
{
abstract override void DoSomeStuff();
}
If abstract override on abstract was illegal, changing DoSomeStuff on Foo to abstract would now prevent Bar from compiling. The abstract override is redundant, but there's no potential negative side effects, so the compiler is okay with this.
The compiler produces warnings for certain things that represent risk: non-explicit method hiding, unreachable code, using obsolete methods, etc. The only "problem" an unnecessary abstract override could indicate is that the code was not efficiently written. That's not something the compiler cares about.
Not functionally. However, there are a few use cases where you might intentionally do so:
- To improve the "readability" of the code. Having the redundant abstract override would serve as a reminder that the method is abstract.
- If future changes to the base class include providing a virtual implementation, you can preemptively prevent some classes from accessing that base class.
- If the abstract override is redundant because the base class was changed from a virtual implementation to abstract, it can safely be left alone.
这篇关于为什么我重写抽象抽象方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!