微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐