与替代相关联的密封关键字 [英] Sealed keyword in association with override

查看:76
本文介绍了与替代相关联的密封关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类似以下代码的方法的签名中,是否总是有必要在sealed关键字后加上override:

Is it always necessary to follow the sealed keyword with override in the signature of a method like the below code:

public sealed override string Method1(){.....}

我的意思是,如果我想在基础类中密封"该方法而不进行覆盖,那么是否仍然需要override关键字?

I mean, if I want to "seal" the method within the base class without overriding, is the override keyword still necessary?

推荐答案

仅在覆盖方法时才有意义.

Sealing a method only makes sense if you override it.

在这里发生的事情如下:
您正在从基类(override)重写方法,并告诉编译器不再允许从您的类派生的类重写此方法(sealed).

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).

如果该方法是您在您的类中声明的新方法,并且您想防止派生类覆盖它,则只需不要将其声明为虚拟方法即可.

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.

这篇关于与替代相关联的密封关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆