ASP.NET - 剃刀静态变量寿命?

发布于 2025-01-07 00:26:49 字数 540 浏览 4 评论 0原文

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

MyClass.cshtml 位于 App_Code:

 @functions
 {
    public static string x;

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

WithSet.cshtml 位于根部:

@{
    MyClass.setX();    
}

@MyClass.x

WithSet.cshtml 位于根部:

@MyClass.x

当我访问 WithSet.cshtml 时,MyClass.x 将被设置为“一些数据”之后,当我访问 WithoutSet.cshtml 时,MyClass.x 仍然包含“一些数据”。我期望该类是新鲜的,而不是初始化的,所以 MyClass.x。我想我不太明白这是怎么回事,班级的寿命是多少?这里的类是静态的吗?

I have three .cshtml created using WebMatrix:

MyClass.cshtml located at App_Code:

 @functions
 {
    public static string x;

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

WithSet.cshtml located at the root:

@{
    MyClass.setX();    
}

@MyClass.x

WithoutSet.cshtml located at the root:

@MyClass.x

When I visit WithSet.cshtml, MyClass.x will be set to "some data" and after that, when I visit WithoutSet.cshtml, still the MyClass.x contains "some data". I was expecting that class to be fresh, not initialized and so MyClass.x. I think I don't fully understand what is going on, what is the life span of the class? Is the class here static?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缺⑴份安定 2025-01-14 00:26:49

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

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

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

Because static objects are shared across the app domain in .net - all users will get the same instance of the class with that static variable having been set.

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

There is a good explanation of what the implications of using static fields in .net are.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文