在ASP.NET中使用静态变量来代替Application变量

A key reason that the Application object exists in ASP.NET is for compatibility with classic ASP code—to allow easier migration of existing applications to ASP.NET. If you are creating an ASP.NET application from scratch, you will want to consider storing data in static members of the application class rather than in the Application object. This will yield a performance increase over using the Application object. An explanation of using statics, as well as some sample code, is listed in Microsoft Knowledge Base article Q312607: INFO: Application Instances, Application Events, and Application State in ASP.NET.

 

In traditional ASP, we always had the Application object to store application-wide variables in.  This of course came at the price of memory allocations.  In .NET we can now take advantage of Static Variables, which in most cases can be faster than accessing the Application object.
In .NET, most objects are actually classes, and Global.asax is no exception.  To take advantage of this, we first have to give our Global.asax a Classname.  We do this by adding the directive naming mine 'MyGlobals':
<%@ Application Classname="MyGlobals" %>
Then, we specify our Static Variable inside the script tags, using the 'Public' and 'Shared' keywords in the Global.asax:
VB:
<Script language="vb" runat="server">
Public Shared sGreeting as String = "Visit HarrisonLogic.com!"
</Script>
C#:
<Script language="C#" runat="server">
Public Static String sGreeting = "Visit HarrisonLogic.com!"
</Script>
Now that we have the variable 'sGreeting' set up, we can call it directly from our .aspx page using the Class name and the Variable name:
x = MyGlobals.sGreeting
Give it a shot!

 

http://weblogs.asp.net/plip/archive/2003/12/01/40526.aspx

http://www.c-sharpcorner.com/UploadFile/charrison/DotNETStaticVariablesBetterthanApplication11292005064803AM/DotNETStaticVariablesBetterthanApplication.aspx

http://stackoverflow.com/questions/303725/asp-net-application-state-vs-a-static-object

转载于:https://www.cnblogs.com/emanlee/archive/2010/01/27/1657902.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值