简体   繁体   English

使用与班级成员密封的运算符

[英]Using operator sealed with the members of the class

I've found in the Troelsen's book, that operator sealed can be used on the members of the class to protect virtual methods from the override . 我在Troelsen的书中发现, 密封的运算符可用于类的成员上,以保护虚拟方法免受override的影响

But if I don't want to override a virtual methods, what sense to make it virtual ? 但是,如果我不想覆盖 虚拟方法,将其虚拟化有什么意义?

You might have a situation like this: 您可能会遇到以下情况:

public class A
{
    public virtual void MyMethod()
    {
        //...
    }
}


public class B : A
{
    public override void MyMethod()
    {
        //...
    }
}


public class C : B
{
    public override void MyMethod()
    {
        //...
    }
}

But what if you want for the inheriting class C NOT to be able to override B 's MyMethod , while still allowing B to override A 's? 但是,如果您希望继承类C不能覆盖BMyMethod ,而仍然允许B覆盖A呢? Then you can do: 然后,您可以执行以下操作:

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

With this change made, you can no longer override the method in C . 进行此更改后,您将无法再覆盖C的方法。

In this context, consider the following example: 在这种情况下,请考虑以下示例:

public class A
{
    public virtual void SomeMethod() { }
}

public class B : A
{
    public sealed override void SomeMethod() { }
}

public class C : B
{
    public override void SomeMethod() { }
}

In this example, without the use of the sealed keyword on SomeMethod in class B , class C would be able to override it because it's original declaration was as virtual . 在此示例中,无需使用class B SomeMethod上的sealed关键字, class C将能够覆盖它,因为它的原始声明为virtual The sealed keyword in this context generates a compiler error. 在这种情况下, sealed关键字会生成编译器错误。 See the MSDN for more information . 有关更多信息,请参见MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM