简体   繁体   中英

Should I call the base class implementation when overriding a method in C# for ASP.NET?

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*/                    
}

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.

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.

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.

这取决于您是否要替换完成基本实现...在大多数情况下,您应该调用基本实现(对于CreateChildItems方法,您肯定应该执行此操作...)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM