Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#静态成员问题_C# - Fatal编程技术网

C#静态成员问题

C#静态成员问题,c#,C#,例如,我有以下静态类: public static class f { public static bool IS_GUEST = (HttpContext.Current.Session["uid"] == null); public static bool IS_ADMIN = (HttpContext.Current.Session["admin"] != null); //... 现在,如果我检查该用户是否为来宾,则即使该用户不是来宾(会话“uid”确实存在),

例如,我有以下静态类:

public static class f
{
    public static bool IS_GUEST = (HttpContext.Current.Session["uid"] == null);
    public static bool IS_ADMIN = (HttpContext.Current.Session["admin"] != null);
    //...
现在,如果我检查该用户是否为来宾,则即使该用户不是来宾(会话“uid”确实存在),我也会得到true。不管发生什么事,我总是错的。会话是在我调用IS_GUEST和IS_ADMIN之前创建的,如果我手动检查它(
HttpContext.Currest.Session[something]
),它可以正常工作。
那么这里的问题是什么呢?

静态初始值设定项在代码中的任何方法之前运行。因此,在初始化字段时,很可能HttpContext.Current.Session尚未初始化。将它们更改为属性,一切都应按预期工作

  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);
        }
     }

当来宾/管理员登录时,您必须设置这些值。

除了DeCaf所说的之外,应用程序域中的所有线程都共享静态字段


在该应用程序域中运行的所有请求将在给定时间点共享相同的值。

最好将会话中的值存储在静态变量中。首先,会话中的值可能会更改,但静态变量不会更改

可能您正在寻找以下内容:

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;
        }
    }

    //...
}

在这种情况下,您可以访问静态变量,如
F.IsGuest
,并将向您提供最新信息。

通过发布实际来源进行澄清。:)哦,是的,现在工作很好(你忘了返回IS_ADMIN btw)。我考虑过get/set,但出于某种原因我没有这么做..见鬼,这解决的另一件事是让第一个用户永久地为每个用户设置值。静态字段将只分配一次。使用带有getter的属性,每次引用该属性时都会对值进行求值,并将对应于每个用户的会话,而不是导致设置值的第一个会话(如果可能的话)。