gpt4 book ai didi

c# - 在 C# 中实现模板方法模式

转载 作者:太空狗 更新时间:2023-10-29 21:13:42 24 4
gpt4 key购买 nike

模板方法 模式规定抽象基类有一个不可重写的方法:该方法实现了通用算法,不应在子类中重写。在 Java 中,模板方法在抽象基类中声明为 final,在 C# 中,sealed 关键字具有类似的含义,但不能声明未覆盖的方法 密封

public abstract class Base
{
protected abstract AlgorithmStep1();

protected abstract AlgorithmStep2();

public sealed void TemplateMethod() // sealed: compile error
{
AlgorithmStep1();
AlgorithmStep2();
}
}

我该如何解决这个问题?为什么不能防止方法可以被子类覆盖(在 C# 中)?

最佳答案

sealed修饰符仅对覆盖基类成员的函数成员有效,以阻止它们对于派生类是虚拟的。默认情况下,函数成员在 C# 中是非虚拟的(与 Java 不同)。不过,对于,您仍然需要 sealed 修饰符 - 默认情况下,类不是密封的。

只需从您的方法中删除 sealed 修饰符,就可以了。

有关密封方法的更多详细信息,请参阅 C# 4 规范的第 10.6.5 节(密封属性和事件分别在第 10.7.5 节和第 10.8.4 节中)。

When an instance method declaration includes a sealed modifier, that method is said to be a sealed method. If an instance method declaration includes the sealed modifier, it must also include the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method.

关于c# - 在 C# 中实现模板方法模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11974371/

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