密封必须与覆盖一起使用?

时间:2014-01-23 18:12:49

标签: c# sealed

来自msdn sealed (C# Reference)

  

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

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

4 个答案:

答案 0 :(得分:10)

sealed可防止子类覆盖某个方法。 如果标记为密封的方法首先不能覆盖,为什么要将其标记为密封?

答案 1 :(得分:3)

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

基本上,它是说子类必须按照你想要的方式使用属性。

答案 2 :(得分: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"); }
}

更多信息:sealed (C# Reference)

答案 3 :(得分: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
    }
}
相关问题