当调用重写方法时如何强制方法调用(在基类中)?
我遇到这种情况,当从 ImplementClass 调用 AbstractMethod 方法时,我想在 AbstractClass 中强制执行 MustBeCalled 方法被调用。 我以前从未遇到过这种情况。 谢谢你!
public abstract class AbstractClass
{
public abstract void AbstractMethod();
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
}
public class ImplementClass : AbstractClass
{
public override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
I have this situation that when AbstractMethod method is invoked from ImplementClass I want to enforce that MustBeCalled method in the AbstractClass is invoked. I’ve never come across this situation before. Thank you!
public abstract class AbstractClass
{
public abstract void AbstractMethod();
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
}
public class ImplementClass : AbstractClass
{
public override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种选择是让抽象类以这种方式进行调用。 否则,C# 中没有办法要求继承类以某种方式实现某个方法。
这样做会在抽象类中创建所需的面向公众的方法,为抽象类提供调用方式和调用顺序,同时仍然允许具体类提供所需的功能。
An option would be to have the Abstract class do the calling in this manner. Otherwise, there is no way in c# to require an inherited class to implement a method in a certain way.
Doing this creates the desired public facing method in the abstract class, giving the abstract class over how and in what order things are called, while still allowing the concrete class to provide needed functionality.
怎么样
How about
为什么不能直接调用Implement类的AbstractMethod()中的方法呢?
Why can't you just call the method in the AbstractMethod() of Implement class?
前面的解决方案忽略的一件事是 ImplementClass 可以重新定义 MethodToBeCalled 而不是调用 MustBeCalled -
如果只有 C# 允许密封非重写方法 - 就像 Java 的 Final 关键字!
我能想到的解决这个问题的唯一方法是使用委托而不是继承,因为类可以定义为密封的。 我使用命名空间和“内部”访问修饰符来防止在实现类上提供新的实现。 另外,要重写的方法必须定义为受保护的,否则用户可以直接调用它。
One thing the preceding solutions ignore is that ImplementClass can redefine MethodToBeCalled and not call MustBeCalled -
If only C# allowed non-overridden methods to be sealed - like Java's final keyword!
The only way I can think of to overcome this is to use delegation rather than inheritance, because classes can be defined as sealed. And I'm using a namespace and the "internal" access modifier to prevent providing a new implementation on implementing classes. Also, the method to override must be defined as protected, otherwise users could call it directly.