在C#中,您可以通过使用public static readonly或const关键字来定义全局常量
方法1:使用public static readonly定义全局常量:
public class Constants { public static readonly string MyConstant = "This is a global constant"; } 然后在其他类中使用它:
public class MyClass { public void PrintConstant() { Console.WriteLine(Constants.MyConstant); } } 方法2:使用const定义全局常量:
public class Constants { public const string MyConstant = "This is a global constant"; } 然后在其他类中使用它:
public class MyClass { public void PrintConstant() { Console.WriteLine(Constants.MyConstant); } } 注意:使用const定义的常量必须在声明时初始化,且不能使用static关键字。而使用public static readonly定义的常量可以在构造函数中初始化。