防止方法在C#中被覆盖 [英] Preventing a method from being overridden in C#

查看:375
本文介绍了防止方法在C#中被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止方法在派生类中被覆盖?

在Java中,我可以通过使用希望防止被覆盖的方法上的final修饰符来做到这一点.

如何在C#中实现相同的目标?
我知道使用sealed,但是显然我只能将其与override关键字一起使用?

class A
{
    public void methodA()
    {
        // Code.
    }

    public virtual void methodB()
    {
        // Code.
    }
}

class B : A
{
    sealed override public void methodB()
    {
        // Code.
    } 
}

因此,在上面的示例中,我可以防止methodB()被类B派生的任何类所覆盖,但是我该如何防止类B首先覆盖methodB()? >

更新:发布此问题时,我错过了A类methodB()声明中的virtual关键字.更正了.

解决方案

您无需执行任何操作. virtual修饰符指定可以重写的方法.省略它意味着该方法是最终的".

具体来说,方法必须是virtualabstractoverride才能被覆盖.

使用new关键字将允许隐藏基类方法,但仍不会覆盖它,即,当您调用A.methodB()时,您将获得基类的版本,但是如果您调用B.methodB(),您将获取新版本.

How do I prevent a method from being overridden in a derived class?

In Java I could do this by using the final modifier on the method I wish to prevent from being overridden.

How do I achieve the same in C#?
I am aware of using sealed but apparently I can use it only with the override keyword?

class A
{
    public void methodA()
    {
        // Code.
    }

    public virtual void methodB()
    {
        // Code.
    }
}

class B : A
{
    sealed override public void methodB()
    {
        // Code.
    } 
}

So in the above example I can prevent the methodB() from being overridden by any classes deriving from class B, but how do I prevent class B from overriding the methodB() in the first place?

Update: I missed the virtual keyword in the methodB() declaration on class A when i posted this question. Corrected it.

解决方案

You don't need to do anything. The virtual modifier specifies that a method can be overridden. Omitting it means that the method is 'final'.

Specifically, a method must be virtual, abstract, or override for it to be overridden.

Using the new keyword will allow the base class method to be hidden, but it will still not override it i.e. when you call A.methodB() you will get the base class version, but if you call B.methodB() you will get the new version.

这篇关于防止方法在C#中被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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