[英]Why can I abstract override an abstract method?
I have an abstract base class: 我有一个抽象的基类:
abstract class Foo
{
virtual void DoSomeStuff()
{
//Do Some Stuff
}
abstract void DoSomeCrazyStuff();
}
And another abstract class derived from that: 另一个抽象类派生自:
abstract class Bar : Foo
{
abstract override void DoSomeStuff();
abstract override void DoSomeCrazyStuff();
}
I understand why you'd want to abstract override DoSomeStuff()
- it will require an new implementation for further derived classes. 我理解你为什么要抽象覆盖
DoSomeStuff()
- 它将需要一个新的实现进一步派生类。 But I can't figure out why you would want to abstract override DoSomeCrazyStuff()
. 但我无法弄清楚你为什么要抽象覆盖
DoSomeCrazyStuff()
。 As far as I can tell, it's redundant - I'm pretty sure removing it would have zero negative impact. 据我所知,这是多余的 - 我很确定删除它会产生零负面影响。
Is there some use case where abstract override on an abstract does something useful? 是否有一些用例,抽象覆盖在抽象上有用吗? If not, why isn't there a compiler warning informing me that what I've wrote does nothing?
如果没有,为什么没有编译器警告通知我,我写的东西什么都没做?
Why can I abstract override an abstract method?
为什么我可以抽象覆盖抽象方法?
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. 如果抽象的抽象覆盖是非法的,将Foo上的DoSomeStuff更改为abstract现在会阻止Bar编译。 The abstract override is redundant, but there's no potential negative side effects, so the compiler is okay with this.
抽象覆盖是多余的,但没有潜在的负面影响,所以编译器对此没问题。
Why isn't there a compiler warning informing me that what I've wrote does nothing?
为什么没有编译器警告告诉我我写的东西什么都没做?
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.
这不是编译器所关心的。
Is there some use case where abstract override on an abstract does something useful?
是否有一些用例,抽象覆盖在抽象上有用吗?
Not functionally. 不是功能性的。 However, there are a few use cases where you might intentionally do so:
但是,有一些用例可能会故意这样做:
By explicitly abstract override
ing it in Bar
you make sure it's going to be seen as abstract by Bar
s descendents even though in the future in Foo
it may be changed into a non-abstract one. 通过在
Bar
明确地abstract override
它,你可以确保它被Bar
的后代视为抽象,即使将来在Foo
它可能会变成非抽象的。 Despite such change, Bar
s descendants will work with the same contract. 尽管有这样的改变,
Bar
的后代将使用同样的合同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.