开发者

Is it bad to declare a page variables in ASP.NET?

Not sure if "page variable" is the right word, but i'm thinking something like this:

using System;
.
.
.

namespace whatever
{
    public partial cl开发者_C百科ass Submit : Page
    {
       int id;
       protected void Page_Load()
       {
          id = getid();
       }
.
.
.

Obviously I will be using id at some point later (not in PageLoad). Seems like it would be better than going through the logic to get it every time. Are there any drawbacks to doing it this way?


Perfectly valid and normal. You might want to declare your fields as protected so they can be used from the markup.


The logic should be to same as class variables, if id is expensive to generate, then save it in a page variable.

Unless you want it to persist across Post Backs, in which case you can use the Session object to save the value. e.g. Session["key_to_object"] = id;


The terminology you are looking for is scope. No, there's nothing at all wrong here, and this use in particular seems very appropriate. It would be inefficient to re-obtain the ID with your function each each time you are using it, and the scope of use is for the whole class.

In general, the scope should be determined by who needs to use the variable, and to some extent, as @Y Low says, the cost of creating it. That is, sometimes you might want to declare something outside the scope of a function even if the function is the only place it gets used.

For example, if you had a function that gets called thousands of times within your class (say, to format a value as a string in some special way), and it needed to declare some variables internally, it would be more efficient to declare them externally to the function, and reduce the overhead each time the function was called.

That may be TMI. In any event, in your case, though, since you say "id" is used elsehere in the class scope, it's entirely appropriate to define it there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜