溫馨提示×

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

c#
小樊
186
2024-08-29 19:56:28
欄目: 編程語言

在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定義的常量可以在構造函數中初始化。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女