Mocking global variables in C#
C# does not allow the declaration of true global variables (existing outside any class scope) like other languages. However, there is a way to simulate this functionality efficiently.
Static class method
The standard solution is to create a static class that contains the global variables you want to share between all classes in your application. An example is as follows:
<code class="language-csharp">public static class 全局变量 { public const int BUFFER_SIZE = 512; public static string FILE_NAME = "Output.txt"; public static readonly string CODE_PREFIX = "US-"; }</code>
How to use
To access these global variables, you simply reference them in your code:
<code class="language-csharp">string code = 全局变量.CODE_PREFIX + value.ToString();</code>
Namespace considerations
If you want to access these variables from a different namespace, you have two options:
全局变量
class outside of any namespace, making it part of the global application namespace. 全局变量
directive in the namespace from which you want to access the variables in the using
class. Advantages
Conclusion
By using static classes, C# developers can effectively simulate the behavior of global variables, providing a convenient and easy-to-maintain method for sharing data across multiple classes and namespaces.
The above is the detailed content of How Can I Effectively Simulate Global Variables in C#?. For more information, please follow other related articles on the PHP Chinese website!