I want to implement a shopping basket.
I created a shopping basket class, and included all the functions inside it that basket will need.
It works OK, but on every content page I need the lines:
Basket myBasket = new Basket(开发者_如何学JAVA);
myBasket.drawBasket();
Is there anyway to get that code to execute on every page without having to manually create the class and run it? Perhaps not use classes?
It really depends on what that code is doing, how does it affect the website, do you need to handle concurrency?
If you're using Master Pages (i hope you are), just put the code in one of the Page-level event handlers there, where all your pages derive from. If you have multiple master pages, these should themselves have a master, so in that case you could put it there.
Again though, it depends on that code - what it is doing? The fact it returns void scares me - sounds like you are changing the state of something.
Generally if you need to execute some arbitrary code (and thats all i know about your example, that it is 'some code') on every page request, it sounds like a case for a static method/property. I dont like the sound of "newing-up" a Basket on each page? Are you planning on creating/disposing of a "Basket" object on every single page request?
Create base page.Add the code in the base page. Inherit your content pages from this base page.
If you're using master pages then you should only need to put the code on the codebehind of your masterpage file.
If you need more control of where and when you render the basket create a usercontrol and put your basket code within this. You can place the markup for inclusion of the usercontrol on any page you like, but will still gain the advantage of only needing to update the code in one place if an update is required. Here is a link on creating using controls. http://msdn.microsoft.com/en-us/library/wt3k2fyw.aspx
精彩评论