必须使用override关键字来sealed吗?

5

来自msdn sealed (C#参考)

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

为什么它必须始终与override一起使用?


7
如果在基类中没有被标记为virtual,那么这个方法已经被有效地封闭了,所以明确标记方法为sealed只有在不想进一步覆盖它时才有意义。 - Jonathan Lonowski
4个回答

10

sealed 可以防止子类重写方法。 如果原本该方法就不能被重写,为什么还要将其标记为 sealed 呢?


3

由于结构体被隐式封闭,它们不能被继承,“sealed”防止子类重写方法。

请参见以下示例:在下面的示例中,Z从Y继承,但Z无法覆盖在X中声明并在Y中封闭的虚拟函数F。

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()被定义为sealed,则无法覆盖该函数,因为它被定义为“sealed”。

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# 参考)


3

因为没有理由将其添加到不覆盖另一个类的属性中。如果在派生类的属性上放置sealed修饰符,那么就意味着任何从您派生的类都不能进一步覆盖该属性。如果该属性从一开始就不可重写,那么使用sealed就没有意义。

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


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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接