[英]Sealed keyword in association with override
Is it always necessary to follow the sealed
keyword with override
in the signature of a method like the below code:是否总是需要在如下代码的方法签名中跟随sealed
关键字和override
:
public sealed override string Method1(){.....}
I mean, if I want to "seal" the method within the base class without overriding, is the override
keyword still necessary?我的意思是,如果我想在基类中“密封”方法而不覆盖,是否仍然需要override
关键字?
Sealing a method only makes sense if you override it.密封一个方法只有在你覆盖它时才有意义。
What happens here is the following:这里发生的事情如下:
You are overriding a method from a base class ( override
) and tell the compiler that classes derived from your class are no longer allowed to override this method ( sealed
).您正在覆盖基类中的方法 ( override
) 并告诉编译器不再允许从您的类派生的类覆盖此方法 ( sealed
)。
If the method is a new one declared by you in your class and you want to prevent derived classes from overriding it, simply don't declare it as virtual.如果该方法是您在您的类中声明的新方法,并且您希望防止派生类覆盖它,则不要将其声明为虚拟方法。
If the method is declared in a base class but is not overridable sealing it wouldn't make any sense, because it already can't be overriden.如果该方法是在基类中声明的,但不是可覆盖密封的,那么它就没有任何意义,因为它已经无法被覆盖。
I think Mr. Hilgarth has provided the best answer here , but just to add something new for programmers who have a previous background in Java (like myself), I think most programmers new to C#, tend to confuse sealed
with final
in Java
with respect to overriding.我认为 Hilgarth 先生在这里提供了最好的答案,但只是为了为以前有Java背景的程序员(比如我自己)添加一些新内容,我认为大多数 C# 新手,倾向于混淆sealed
和final
in Java
压倒一切。
In Java , the default behaviour without specifying "any"
modifier is that the method can be overriden in its derived classes.在Java中,不指定"any"
修饰符的默认行为是该方法可以在其派生类中被覆盖。
While in C# , the default behaviour is that the method cannot be overriden unless explicitly specified using the virtual
keyword.而在C#中,默认行为是除非使用virtual
关键字明确指定,否则无法重写该方法。
Hope this helps to supplement the best answer above.希望这有助于补充上面的最佳答案。
Is it always necessary to follow the sealed
keyword with override
in the signature of a method like the below code:是否总是需要在方法的签名中使用override
跟随sealed
关键字,如下面的代码:
public sealed override string Method1(){.....}
I mean, if I want to "seal" the method within the base class without overriding, is the override
keyword still necessary?我的意思是,如果我想在不覆盖的情况下“密封”基类中的方法,是否仍然需要override
关键字?
Well, it technically is possible.... however, the solution is in my option kinda dirty.好吧,这在技术上是可能的……但是,我的选择是解决方案有点脏。
Imagine having a class A
(either in your code base or an external library):想象一下有一个A
类(在您的代码库或外部库中):
public class A
{
public virtual void M () { /* implementation */ }
}
You could define an (abstract) class B: A
as follows:您可以定义一个(抽象)类B: A
,如下所示:
public class B : A
{
public sealed override void M() => base.M();
}
Any class C: B
would not be able to override AM
as you have sealed the method (even though you made no semantic changes).任何类C: B
都无法覆盖AM
,因为您已经密封了该方法(即使您没有进行任何语义更改)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.