在C#.NET全局变量 [英] Global variables in c#.net

查看:910
本文介绍了在C#.NET全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I set a global variable in a C# web application?

我想要做的是设置页面(母版页也许)一个变量,并从任何页面访问这个变量。

What I want to do is to set a variable on a page (master page maybe) and access this variable from any page.

我想使用没有缓存,也没有会议。

I want to use neither cache nor sessions.

我觉得我必须使用Global.asax中。任何帮助?

I think that I have to use global.asax. Any help?

推荐答案

从任何地方使用公共静态类,并对其进行访问。

Use a public static class and access it from anywhere.

public static class MyGlobals {
    public const string Prefix = "ID_"; // cannot change
    public static int Total = 5; // can change because not const
}

用于像这样,从母版页或其他地方:

used like so, from master page or anywhere:

string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();

您不必使类的一个实例;其实你不能因为它是静态的。 <击> 只需直接使用它。内部的静态类中的所有成员也必须是静态的。字符串preFIX没有标记静态的,因为常量本质上是隐含静态的。

You don't need to make an instance of the class; in fact you can't because it's static. new Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because const is implicitly static by nature.

静态类可以在你的项目中的任何地方。它并不必须是Global.asax中的一部分或任何特定的页面,因为它的全球性(或至少尽可能接近我们可以得到在面向对象的术语的概念。)

The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)

只要你喜欢你可以使尽可能多的静态类和任何你想要他们的名字。

You can make as many static classes as you like and name them whatever you want.

有时候程序员喜欢组的常量使用嵌套静态类。例如,

Sometimes programmers like to group their constants by using nested static classes. For example,

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";
    }
}

和访问他们像这样:

MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;

这篇关于在C#.NET全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆