c#.net中的全局变量

sca*_*man 44 .net c# global-variables

如何在C#Web应用程序中设置全局变量?

我想要做的是在页面上设置变量(可能是母版页)并从任何页面访问此变量.

我想既不使用缓存也不使用会话.

我认为我必须使用global.asax.有帮助吗?

Joh*_*n K 103

使用公共静态类并从任何地方访问它.

public static class MyGlobals {
    public const string Prefix = "ID_"; // cannot change
    public static int Total = 5; // can change because not const
}
Run Code Online (Sandbox Code Playgroud)

像这样使用,从母版页或任何地方:

string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();
Run Code Online (Sandbox Code Playgroud)

您不需要创建类的实例; 事实上你不能因为它是静态的.new只需直接使用它.静态类中的所有成员也必须是静态的.字符串Prefix未标记为静态,因为const本质上是隐式静态的.

静态类可以位于项目的任何位置.它不必是Global.asax或任何特定页面的一部分,因为它是"全局的"(或者至少尽可能接近我们在面向对象术语中的概念.)

您可以根据需要创建任意数量的静态类,并根据需要为其命名.


有时程序员喜欢使用嵌套的静态类对其常量进行分组.例如,

public static class Globals {
    public static class DbProcedures {
        public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
        public const string Sp_Get_Names = "dbo.[Get_First_Names]";
    }
    public static class Commands {
        public const string Go = "go";
        public const string SubmitPage = "submit_now";
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样访问它们:

MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;
Run Code Online (Sandbox Code Playgroud)

  • +1优雅的解决方案 - 很好,我喜欢它. (2认同)

Ron*_*ein 6

我是第二个jdk的答案:你的应用程序的任何类的任何公共静态成员都可以被视为"全局变量".

但是,请注意这是一个ASP.NET应用程序,因此,它是全局变量的多线程上下文.因此,在向这些变量更新和/或从这些变量读取数据时,应使用某种锁定机制.否则,您可能会使数据处于损坏状态.