gpt4 book ai didi

c# - 为什么在当前类是子类时对方法或属性使用 sealed

转载 作者:行者123 更新时间:2023-11-30 19:59:46 26 4
gpt4 key购买 nike

当当前类曾经从父类(super class)继承时,为什么我们要在方法或属性上使用 sealed 关键字?假设我们创建了一个类,并且倾向于将它的一个或多个方法暴露给对象用户,但根本不让它被继承,并使用sealed 来解决这个问题。那么,为什么不呢?仅密封当前继承类的方法或属性背后的原因是什么?

最佳答案

如 MSDN 文档中所述 sealed :

You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

换句话说,您可以阻止覆盖发生在类继承层次结构的更下方。作为一名程序员,您基本上是在说这个特定方法应该与所有子类具有共同的功能。

这是同一篇文章中的一个很好的代码示例:

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

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

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 方法的可能应用。

abstract class Car
{
public abstract void Make();
}

class Ford : Car
{
// We don't want someone inheriting from this class to change the
// 'Make' functionality - so we seal the method from being further
// overridden down the inheritance hierarchy
sealed public override void Make() { Console.WriteLine("Ford"); }
}

// This way there is no way (besides shadowing) someone inheriting from Ford
// can change the behavior of Make() - so these two types will contain the
// same behavior. Pretty nice, eh!?
class Focus : Ford
{
}

class Escape : Ford
{
}

关于c# - 为什么在当前类是子类时对方法或属性使用 sealed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23034919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com