Should I call the base class implementation when o

2019-04-28 00:25发布

问题:

I understand overriding a method/function redefines its implementation in the derived class from its implementation in the base class.

Now what confuses me, is if I override a class in ASP.NET such as CreateChildControls() (I picked it randomly for no particular reason), VS2008 auto generates:

protected override void CreateChildControls()
{
   base.CreateChildControls();
}

Good enough, the default implementation just calls the base class' CreateChildControls().

So if I want to run some code, since I do not know how base.CreateChildControls(), should I do this:

protected override void CreateChildControls()
{
   /*My Code Here*/                    
   base.CreateChildControls();
}

or, ignore what base.CreateChildControls() altogether and just do

protected override void CreateChildControls()
{
   /*My Code Here*/                    
}

回答1:

That's up to you. Generally, you want to call the base class method because it might do a lot of stuff you're not privy to (especially in a class you don't control .. get it? Control.) But, if you are very confident you don't need (or want) the base class "stuff" to happen, you can remove the call.



回答2:

It's simply a question of whether you want to entirely replace the behavior or add behavior.

For something like CreateChildControls, you will probably retain the call to the base class.



回答3:

it depends on what you want to do. If you want the base.CreateChildControls() method to be called and then you want to perform some custom action before or after the method is called, then you can do so.

If you want to have complete control of what is happening when CreateChildControls is called, then you can simply ignore calling it altogether.

The fact that it's in there by default is just a bit of guidance for you.



回答4:

It depends if you want to replace or complete the base implementation... in most cases you should call the base implementation (and you definitely should do it in the case of the CreateChildItems method...)



回答5:

You might want to take a look at the template method pattern. While you can't do anything about the way the library classes are implemented, it might help you ensure the code you write is easy to use correctly.