5

来自 msdn密封(C# 参考)

“当应用于方法或属性时,密封修饰符必须始终与覆盖一起使用。”

为什么必须始终与覆盖一起使用?

4

4 回答 4

10

sealed防止方法被子类覆盖。如果标记为密封的方法一开始就不可覆盖,为什么要将其标记为密封?

于 2014-01-23T18:17:03.133 回答
3

因为没有理由将它添加到不覆盖另一个类的属性的属性中。如果您将sealed 修饰符放在派生类的属性上,则表示从您派生的任何人都不能进一步覆盖该属性。如果该属性从一开始就不能被覆盖,那么使用sealed 是没有意义的。

基本上,它是说子类必须按照您的意图使用该属性。

于 2014-01-23T18:20:51.120 回答
3

因为结构是隐式密封的,它们不能被继承,“密封”防止方法被子类覆盖。

请参阅示例:In the following example, Z inherits from Y but Z cannot override the virtual function F that is declared in X and sealed in Y.

class X
{
    protected virtual void F() { Console.WriteLine("X.F"); }
    protected virtual void F2() { Console.WriteLine("X.F2"); }
}

Y类继承自X类,将函数F()定义为:sealed protected override void F()。

class Y : X
{
    sealed protected override void F() { Console.WriteLine("Y.F"); }
    protected override void F2() { Console.WriteLine("Y.F2"); }
}

从 Y 继承的类 Z,其中函数 F() 被定义为密封,您不能覆盖该函数,因为它定义为“密封”

class Z : Y
{
    // Attempting to override F causes compiler error CS0239. 
    // protected override void F() { Console.WriteLine("C.F"); }

    // Overriding F2 is allowed. 
    protected override void F2() { Console.WriteLine("Z.F2"); }
}

更多信息:密封(C# 参考)

于 2014-01-23T18:25:49.380 回答
0

假设你有:

public BaseClass
{
    public virtual void SomeMethod() 
    {
    }
}

和:

public MyDerivedClass : BaseClass
{
     public void AnotherMethod()
     {
         // there's no point sealing this guy - it's not virtual
     }

     public override sealed void SomeMethod()
     {
         // If I don't seal this guy, then another class derived from me can override again
     }
}

接着:

public class GrandChildClass : MyDerivedClass
{
    public override void AnotherMethod()
    {
        // ERROR - AnotherMethod isn't virtual
    }

    public override void SomeMethod()
    {
        // ERROR - we sealed SomeMethod in MyDerivedClass
        // If we hadn't - this would be perfectly fine
    }
}
于 2014-01-23T18:25:22.863 回答