防止重写 C# 中的各个方法
我知道我可以使用sealed来防止其他类继承某个类, 但是是否可以允许继承但防止重写某些虚拟方法?
I know that I can use the sealed in order to prevent other classes to inherit a certain class,
but is it possible to allow inheritance but prevent overriding of some virtual methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只能重写
虚拟
方法。只要省略
virtual
,你的方法就不会被重写。Only
virtual
methods can be overridden.Just leave out
virtual
, and your method will not be overridable.您还可以使用 seal 修饰符来防止派生类进一步重写该方法。
看看这个:密封方法
you can also use sealed modifier to prevent a derived class from further overriding the method.
check this out: Sealed methods
是的。
sealed
关键字也可以用在方法上,表示在较高继承级别上是虚拟或抽象的方法不能被进一步继承。如果该方法一开始就不是虚拟或抽象的,不用担心;它不能被覆盖。
请注意,
sealed
仅影响方法重写;方法隐藏不能以这种方式停止,因此子类仍然可以声明一个与密封方法同名和签名的new
方法。Yes. The
sealed
keyword can also be used on methods, to indicate that a method which is virtual or abstract at higher inheritance levels cannot be further inherited.If the method was never virtual or abstract to begin with, no worries; it can't be overridden.
Note that
sealed
only affects method overriding; method hiding cannot be stopped in this way, so a child class can still declare anew
method of the same name and signature as your sealed method.您可以通过使抽象类本身从某些东西派生来获得
sealed
关键字来处理抽象类中的方法:仍然从原始(现在是派生的)抽象类派生您的具体类:
但是,没有什么可以阻止实现者
new
它:You can get the
sealed
keyword to work on a method in the abstract class by making that abstract class itself derived from something:Still deriving your concrete class from the original (and now derived) abstract class:
There is nothing, however to prevent an implementer from
new
ing it:您可以通过两种方式使用
sealed
关键字:为了允许继承,请勿将
sealed
关键字放在类之前,并避免覆盖,将sealed
放在您不希望被覆盖的函数之前。You can use the
sealed
keyword in two ways:To allow inheritance don’t put the
sealed
keyword before the class and to avoid overriding putsealed
before the function which you don’t want to be overridden.是的。您需要使用密封覆盖来实现它的方法。
Yes. you need to use sealed override for the method to achieve it.