Make sure base method gets called in C#
Make sure base method gets called in C#
Can I somehow force a derived class to always call the overridden methods base?
public class BaseClass
{
public virtual void Update()
{
if(condition)
{
throw new Exception("..."); // Prevent derived method to be called
}
}
}
And then in a derived class :
public override void Update()
{
base.Update(); // Forced call
// Do any work
}
I've searched and found a suggestion to use a non-virtual Update() but also a protected virtual UpdateEx(). It just doesn't feel very neat, isn't there any better way?
I hope you get the question and I am sorry for any bad English.
回答1
Use the template method pattern - don't override the base method which needs to do some work, override one specific bit, which can either be abstract or a no-op in the base class. (The decision about whether to make it a no-op or abstract is usually fairly obvious - does the base class make sense on its own, as a concrete class?)
It sounds like this is basically the pattern you've found with UpdateEx
- although it's usually UpdateImpl
or something similar in my experience. There's nothing wrong with this as a pattern, in my view - it avoids any idea of forcing all derived classes to write the same code to call the base method.
回答2
This took me a bit to get what Update and UpdateEx would look like. Here's a code example that might help others.
public class BaseClass
{
// This is the Update that class instances will use, it's never overridden by a subclass
public void Update()
{
if(condition);
// etc... base class code that will always run
UpdateEx(); // ensure subclass Update() functionality is run
}
protected virtual void UpdateEx()
{
// does nothing unless sub-class overrides
}
}
A subclass will never have any implementation for Update(). It'll uses UpdateEx() to add implementation to Update();
public class ConcreteClass : BaseClass
{
protected override void UpdateEx()
{
// implementation to be added to the BaseClass Update();
}
}
Any instance of ConcreteClass will use the BaseClass implementation of Update() along with however ConcreteClass extends it with UpdateEx().
我遇到的问题是多次继承,
Base
A:Base
B:A
A override method1 of Base
B need add some extra work beyond method1
所以,方法2更适合我,在A里面新加一个virtual方法,然后直接在A里面method1里面,新加的virtual方法
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2020-05-12 WaitAll vs WhenAll
2020-05-12 When does a C# Task actually start?
2020-05-12 What are 'closures' in .NET?
2019-05-12 UML的类型
2017-05-12 IIS Modules Overview
2017-05-12 Introduction to IIS Architectures