如何访问Global.asax静态成员?

发布于 2024-10-10 02:52:13 字数 279 浏览 4 评论 0原文

如果我们在 Global.asax 中声明一个 static 变量,那么如何在 ASP.NET 页面中访问它?

<script runat=server">

   public static object myObject = new MyClass();

   // Application_Start() and other stuff goes here.

</script>

而且,这对于存储全局对象(所有请求的同一实例)是一个好主意吗?

If we declare a static variable in Global.asax then how to access it inside an ASP.NET page ?

<script runat=server">

   public static object myObject = new MyClass();

   // Application_Start() and other stuff goes here.

</script>

And, is this a good idea for storing a global object (same instance for all requests) ?

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

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

发布评论

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

评论(4

骷髅 2024-10-17 02:52:13

myObject 应该可用于 global.asax 中和 ASP.NET 页面内的所有方法

Global.myObject

myObject should be available to all the methods in global.asax and inside your ASP.NET pages using

Global.myObject
一花一树开 2024-10-17 02:52:13

将对象创建为单例可能比将其作为“全局”对象更好。在应用程序启动时实例化它,并在应用程序结束时销毁它。只要您不需要它跨网络农场,您就非常安全。

请参阅这篇文章及其评论。

It may be better to create your object as a singleton rather than putting it as a "global" object. Instantiate it in application start, and destroy it in application end. As long as you don't need it to be across web farms, you're pretty safe.

See this post and its comments.

http://weblogs.asp.net/jeff/archive/2007/09/21/how-do-you-get-a-true-singleton-in-an-asp-net-app.aspx

萌面超妹 2024-10-17 02:52:13

就我个人而言,我强烈反对在 ASP.NET 中使用全局变量。几年前我有过相当糟糕的经历。

您应该同步对全局 MyClass 实例的成员的访问,以确保它在多线程场景中正常工作(如果出现多个请求,则可能/强制)。

您还可以使用 ApplicationState根据 Microsoft 的说法,您不应该

Personally, I would strongly vote against using global variables in ASP.NET. I had rather bad experiences some years back.

You should synchronize access to the members of your global MyClass instance to ensure it works correctly in a multi-threading scenario (which is likely/mandatory if multiple requests come in).

There is also the ApplicationState which you could use, according to Microsoft, you shouldn't.

泛滥成性 2024-10-17 02:52:13

全局未定义
这对我有用:

ASP.global_asax
示例

ASP.global_asax.DefaultModel.GetTable("Tags");

Global is not defined
that works for me:

ASP.global_asax
example

ASP.global_asax.DefaultModel.GetTable("Tags");

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