开发者

C# Static members problem

For example, I Have the following static class:

public static class f
{
    public static bool IS_GUEST = (HttpContext.Current.Session["uid"] == null);
    public static bool IS_ADMIN = (HttpContext.Current.Session["admin"] != null);
    //...

Now If i check whether the user is Guest or not using IS_GUEST i always get true even if the user is not a guest (session "uid" does exist). And for IS_ADMIN i get always false, no matter what. The sessions are created before i call IS_GUEST and IS_ADMIN, and if I check it manuall开发者_开发问答y (HttpContext.Currest.Session[something]) it works fine. So what's the problem here?


Static initializers are run before any method in your code. So quite likely the HttpContext.Current.Session has not been initialized when your fields are initialized. Change them to properties and everything ought to work as expected.

  public static class f
  {
     public static bool IS_GUEST
     {
        get
        {
           return (HttpContext.Current.Session["uid"] == null);
        }
     }
     public static bool IS_ADMIN
     {
        get
        {
           return (HttpContext.Current.Session["admin"] != null);
        }
     }


You have to set those values when a guest/admin logs in.


In addition to what DeCaf said, static fields are shared between all threads in the application domain.

All requests that run in that app domain will share the same value at a given point in time.


It's bad idea to store in the static variables values from the Session. First of all value in session may be changed, but your static variable will not change.

probably you are looking something for this:

public static class f
{
    public static bool IsGuest 
    {
        get
        {
            return HttpContext.Current.Session["uid"] == null;
        }
    }

    public static bool IsAdmin
    {
        get
        {
            return HttpContext.Current.Session["admin"] != null;
        }
    }

    //...
}

In this case you can access static variable like F.IsGuest and you will be provided with the up to date information.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜