如何在C#中定义全局常量

   2024-09-30 8270
核心提示:在C#中,您可以通过使用public static readonly或const关键字来定义全局常量方法1:使用public static readonly定义全局常量:pu

在C#中,您可以通过使用public static readonlyconst关键字来定义全局常量

方法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定义的常量可以在构造函数中初始化。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号