ASP.NET - 剃刀静态变量寿命?
我使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于静态对象在 .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.