Home >Backend Development >C++ >How Can I Achieve Global Variable Functionality in C#?
Using global variables in C#
C# does not support traditional global variables (accessible without any instance reference). However, there are some alternatives to achieve the functionality of global variables.
Use static classes
The most straightforward way is to use static classes. Static classes are not instantiated and can contain static members (variables, properties, and methods) and non-static members. Static members are shared among all instances of a class and can be accessed without creating any instance:
<code class="language-c#">public static class 全局变量 { public const Int32 BUFFER_SIZE = 512; // 不可修改 public static String FILE_NAME = "Output.txt"; // 可修改 public static readonly String CODE_PREFIX = "US-"; // 不可修改 }</code>
To access a defined value anywhere in code within the same namespace:
<code class="language-c#">String code = 全局变量.CODE_PREFIX + value.ToString();</code>
Handling different namespaces
To access global variables from different namespaces, there are two ways:
The above is the detailed content of How Can I Achieve Global Variable Functionality in C#?. For more information, please follow other related articles on the PHP Chinese website!