C#全局variables

我如何在C#中声明一个variables,以便每个类(* .cs)都可以访问其内容,而无需实例引用?

在C#中没有这样的全局variables。 期。

你可以有静态成员,如果你想要:

public static class MyStaticValues { public static bool MyStaticBool {get;set;} } 

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

 public static class Globals { public const Int32 VALUE = 10; // Unmodifiable public static String s_Name = "Mike"; // Modifiable public static readonly String s_City = "New York"; // Unmodifiable } 

那么你可以在任何地方使用它,只要你在同一个命名空间上工作,你没有命名空间(所以把它放在全局应用程序的命名空间中),或者如果你在不同的命名空间上工作,就插入正确的using命令:

 string name = Globals.s_Name; 

首先检查一下,如果你确实需要一个全局variables,而不用考虑你的软件体系结构,

我们假设它通过了testing。 根据使用情况的不同,Globals可能会因为竞争条件和许多其他“不好的事情”而难以debugging,所以最好从准备处理这种不好的事情的angular度来处理它们。 所以,

  1. 将所有这些全局variables包装成一个static类(用于可pipe理性)。
  2. 有属性而不是字段(='variables')。 这样,您就有了一些机制来解决将来与Globals并发写入的任何问题。

这样一个class的基本纲要是:

 public class Globals { private static bool _expired; public static bool Expired { get { // Reads are usually simple return _expired; } set { // You can add logic here for race conditions, // or other measurements _expired = value; } } // Perhaps extend this to have Read-Modify-Write static methods // for data integrity during concurrency? Situational. } 

其他类的用法(在相同的命名空间中)

 // Read bool areWeAlive = Globals.Expired; // Write // past deadline Globals.Expired = true;