前言
嗨,大家好!
作為一名 C# 程序員,常量就像我們代碼中的小伙伴,時刻陪伴著我們!
在 C# 中,定義常量有幾種簡單而有效的方法。
今天,我想和大家分享 5 種常用的常量定義方式,為你的編程之旅增添一些樂趣!
1. 使用 const 關鍵字
const
關鍵字用于定義編譯時常量,一旦定義,常量的值不能更改。
public class Example
{
public const int MaxValue = 100;
public const string WelcomeMessage = "Hello, World!";
}
2. 使用 readonly 關鍵字
readonly
修飾符用于定義運行時常量,它的值可以在聲明時或構造函數中設置,但在其他地方不能更改。
public class Example
{
public readonly int num = 100;
public Example()
{
num = 200;
}
}
3. 使用 enum
枚舉
通過定義枚舉,可以創建一組相關的常量值,通常用于整型常量。
public enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
4. 使用 static 字段
static
字段雖然不是嚴格意義上的常量,但在實際運用中通常也用作可共享的類級別常量
public class Example
{
public static int StaticValue = 42;
}
static
還可以結合 readonly
,創建一個更靈活的類級別的常量。
public class Example
{
public static readonly string Url;
static Example()
{
Url = "https://www.example.com";
}
}
5. 使用 init 僅設置屬性
這是 C# 9.0+ 引入的一個新關鍵字,可以讓類型對象的屬性只能在對象初始化時設置,之后不能再修改,雖然不是嚴格意義上的常量,但也有常量的特點
public class Person
{
public string Name { get; init; }
public int Age { get; init; }
public Person()
{
// 可以在這里初始化 init 屬性
Name = "Unknown";
Age = 0;
}
}
// 使用 init 屬性
var person = new Person { Name = "Jacky", Age = 30 };
// person.Name = "Tom"; // 這行代碼會導致編譯錯誤
總結
總結一下:
const
:適用于固定值且不需要在運行時計算的常量
readonly
:適用于在運行時需要初始化,或者依賴于某些條件的常量
static
:雖然不是嚴格意義上的常量,但實踐中通常也用作可共享的類級別常量
init
:雖然不是嚴格意義上的常量,但也有常量的特點,適合增強對象的不可變性,同時保持靈活性
閱讀原文:原文鏈接
該文章在 2025/1/15 10:17:36 編輯過