static variables in asp.net/C#

后端 未结 5 914
夕颜
夕颜 2021-01-02 03:24

I\'m using extensively static variables in my web application project. Now I have read from some articles that it is a global variable for the whole project and the data tha

5条回答
  •  旧巷少年郎
    2021-01-02 04:15

    On static's, there are various reasons why they should be avoided in general, although they do have their specific uses.

    Then i have this requirement that a particular variable has to be initialized only once in a particular webform.aspx.cs and the scope has to be restricted to only to that particular .aspx.cs and to that particular user who has logged in ? How do i meet this requirement ? If possible can any one illustrate this with code ?

    For this requirement, I would suggest you look at clarifiying the requirement:

    • is this once per user? If so, then look at using the Session object provided by ASP. Sample code for Session is http://msdn.microsoft.com/en-us/library/ms972429.aspx
    • or is this once per page per user? i.e. if the same user has two browsers open on the same page, then will the user have two objects? If so, then look at using ViewState within the page. overview of ViewState is http://msdn.microsoft.com/en-us/library/ms972976.aspx

    Personally I prefer using Session - with ViewState it's very easy for things to go wrong, and when they do go wrong it can be very hard to debug!


    explanation of: "when they do go wrong it can be very hard to debug" - ViewState can be configured to works several ways, but generally it's set up to work by serializing objects into the client pages as Hidden form fields and then subsequently deserializing these objects when the page PostBack occurs. I've spent many many days debugging a certain DNN based website which had "Invalid ViewState" problems only on some browsers, only on some pages and only some of the time. What caused this? After several days I still didn't know... hence why I stay clear of ViewState if I can. However, I admit that this might be an unfair decision - in my case, I was working with a lot of third party code which generated dynamic pages and which created a lot of ViewState (size and complexity of ViewState is actually one of my reasons for not using WebForms at all if I can).

提交回复
热议问题