ASP.NET - razor静态变量寿命?

时间:2012-02-20 06:38:02

标签: asp.net variables webmatrix

我使用WebMatrix创建了三个.cshtml:

位于App_Code的MyClass.cshtml:

 @functions
 {
    public static string x;

    public static void setX()
    {
        x = "some data";
    }
}

WithSet.cshtml位于根目录:

@{
    MyClass.setX();    
}

@MyClass.x

位于根目录的WithoutSet.cshtml:

@MyClass.x

当我访问WithSet.cshtml时,MyClass.x将被设置为“某些数据”,之后,当我访问WithoutSet.cshtml时,MyClass.x仍包含“某些数据”。我期待那个课程是新鲜的,没有初始化,所以MyClass.x。我想我不完全明白发生了什么,这个班的寿命是多少?这里的班级是静态的吗?

1 个答案:

答案 0 :(得分:3)

因为静态对象是在.net中的应用程序域之间共享的 - 所有用户都将获得已设置该静态变量的类的相同实例。

http://www.foliotek.com/devblog/avoid-static-variables-in-asp-net/

对.net中使用静态字段的含义有一个很好的解释。

相关问题