在 ASP.NET 中使用 C# 全局变量的正确方法
本文关键字:全局变量 方法 ASP NET | 更新日期: 2023-09-27 18:36:34
我在应用程序中使用了 ASP.NET Web 窗体和 C#。我有一个名为 Global.cs
的类文件,其中我使用 set
和 get
属性定义变量。我通过实例化该类对象在任何页面上的任何位置使用这些变量。
这是我Global.cs
文件:
using System;
using System.Data;
using System.Linq;
using System.Web;
/// <summary>
/// Contains my site's global variables.
/// </summary>
public static class Global
{
/// <summary>
/// Global variable storing important stuff.
/// </summary>
public static string gDate;
public static string gMobLength;
public static string gDateFormat;
public static string gApplicationNo;
public static string gBranchNo;
public static string gMemId;
public static string gIsEditable="false";
public static string gLoggedInUserName;
public static string ImportantData
{
get
{
return gDate;
}
set
{
gDate = value;
}
}
public static string MobileLength
{
get
{
return gMobLength;
}
set
{
gMobLength = value;
}
}
public static string DateFormat
{
get
{
return gDateFormat;
}
set
{
gDateFormat = value;
}
}
public static string ApplicationNo
{
get
{
return gApplicationNo;
}
set
{
gApplicationNo = value;
}
}
public static string BranchNo
{
get
{
return gBranchNo;
}
set
{
gBranchNo = value;
}
}
}
这是在整个项目中使用变量的正确方法吗? 这种方法可能的优点和缺点是什么,你们会采取什么方法来使用全局变量?
首先,我建议使用自动实现的属性。
public static string BranchNo { get; set; }
稍微简化您的代码。至于这是否是一个好方法,这取决于。有时简单明了更好,这属于这一类。如果初始化后值不应更改,则可能需要使用适当的单例进行初始化:
public class Settings
{
private static Settings _current;
private static readonly object _lock = new object();
public static Settings Current
{
get
{
lock(_lock)
{
if (_current == null) throw new InvalidOperationException("Settings uninitialized");
return _current;
}
}
set
{
if (value == null) throw new ArgumentNullException();
if (_current != null) throw new InvalidOperationException("Current settings can only be set once.");
if (_current == null)
{
lock(_lock)
{
if (_current == null) _current = value;
}
}
}
}
public string ImportantData { get; private set; }
// etc.
}
初始化设置:
Settings.Current = new Settings{ ImportantData = "blah blah blah"};
访问:
var data = Settings.Current.ImportantData;
在两个溴化物之外,"全局是坏的"和"属性是好的"......你的方法本质上没有什么问题。 去吧!
恕我直言..PSM
实例化该类对象后看不到该变量的原因是变量被声明为静态变量。静态变量旨在由该庄园使用 ClassName.variableName 或 ClassName.PropertyName