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