When should you call base.Method() in overridden method, and how to mark this when you write code in team?

蹲街弑〆低调 提交于 2019-12-29 04:30:52

问题


When using some framework/api, sometimes it's pretty unclear if you must call base.Method if you override it, for example you can be pretty sure that you should call base.Maethod() when you are overriding event invocater, to propagate the event, in other situations it can be not so clear especially when there is no source code available, and no comments.

I wounder how other programmers decide should they call base method or not in this situation, and if you are about to write some framework how to inform other programmers that you expect base method to be called or not in virtual members.


回答1:


Nowadays I don't think that consumers of a class that override a method should ever need to call base.Method(). The code should be written in such way that it cannot be broken.

public class MyBase
{
    private void FooInternal()
    {
        DoRequiredStuff();
        Foo();
    }
    public virtual void Foo() {}
}



回答2:


If you are requiring that consumers of your class MUST implement functionality of a particular method, that method should be marked abstract.

If consumers of your class should optionally provide functionality of a particular method, that method should be virtual.

There is really no way to require that a consumer of a class call a base.Method() on a virtual method. It really depends on context. If the base.Method() does some work that you'd otherwise have to do, it'd behoove you to call base.Method() if that would save you some development time/it makes sense in that context.




回答3:


It depends on whether the underlying functionality needs to be used.

For example, if the base object has some generic database functionality that needs to be run, call the base method at the end. If your code overwrites some of the properties that the base method will set, rather call the base method first.

If there is no source code or documentation, RedGate's .Net Reflector (http://www.red-gate.com/products/dotnet-development/reflector/) can just unpack the assemblies you are trying to use and you can see how the code works.



来源:https://stackoverflow.com/questions/4721541/when-should-you-call-base-method-in-overridden-method-and-how-to-mark-this-wh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!