在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/p/1657902.html