參考:
const : https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/constants
區(qū)別:
- readonly 關(guān)鍵字不同于 const 關(guān)鍵字垄开。 const 字段只能在該字段的聲明中初始化琴许。 可以在字段聲明和任何構(gòu)造函數(shù)中多次分配 readonly 字段。 因此溉躲,根據(jù)所使用的構(gòu)造函數(shù)榜田,readonly 字段可能具有不同的值。 另外锻梳,雖然 const 字段是編譯時常量箭券,但 readonly 字段可用于運行時常量,如下面的示例所示:
一. const
1. 特點:
- 常量是不可變的值疑枯,在編譯時是已知的辩块,在程序的生命周期內(nèi)不會改變。
- 僅 C# 內(nèi)置類型(不包括 System.Object)可聲明為 const
- 常量在聲明時必須初始化神汹。 例如:
class Calendar1
{
public const int Months = 12;
}
在此示例中庆捺,常量 Months 始終為 12,即使類本身也無法更改它屁魏。 實際上滔以,當(dāng)編譯器遇到 C# 源代碼中的常量標(biāo)識符(例如Months )時,它直接將文本值替換到它生成的中間語言 (IL) 代碼中氓拼。 因為運行時沒有與常量相關(guān)聯(lián)的變量地址
你画,所以 const 字段不能通過引用傳遞抵碟,并且不能作為l-value在表達(dá)式中顯示。
- 常量像靜態(tài)字段一樣被訪問,因為他的值對于所有類型的實例是一樣的。你不需要用static關(guān)鍵字去聲明他們细燎。訪問方式:
int birthstones = Calendar.Months;
二. readonly
1. 使用
readonly關(guān)鍵字是一個可在三個上下文中使用的修飾符:
(1)在字段申明中,readonly可以在字段聲明和構(gòu)造函數(shù)中多次分配敦迄、重新分配。構(gòu)造函數(shù)退出后凭迹,不能分配 readonly 字段罚屋。
其中readonly在值類型和引用類型具有不同的含義:
-
由于值類型直接包含數(shù)據(jù),因此屬于 readonly 值類型的字段不可變
嗅绸。 - 由于引用類型包含對其數(shù)據(jù)的引用脾猛,因此屬于 readonly 引用類型的字段必須始終引用同一對象。 該對象不是不可變的鱼鸠。
readonly 修飾符可防止字段替換為引用類型的其他實例猛拴。 但是,修飾符不會阻止通過只讀字段修改字段的實例數(shù)據(jù)蚀狰。
(2) readonly struct愉昆,readonly 指示 struct 是不可變的。
(3)ref readonly
方法返回中麻蹋,readonly 修飾符指示該方法返回一個引用撼唾,且不允許向該引用寫入內(nèi)容。
2. Readonly struct example
- struct 定義上的 readonly 修飾符聲明該結(jié)構(gòu)是不可變的 哥蔚。
struct 的每個實例字段都必須被標(biāo)記為 readonly
,如下例所示:
public readonly struct Point
{
public double X { get; }
public double Y { get; }
public Point(double x, double y) => (X, Y) = (x, y);
public override string ToString() => $"({X}, {Y})";
}
前面的示例使用只讀自動屬性來聲明其存儲蛛蒙。 該操作指示編譯器為這些屬性創(chuàng)建 readonly 支持字段糙箍。 還可以直接聲明 readonly 字段:
public readonly struct Point
{
public readonly double X;
public readonly double Y;
public Point(double x, double y) => (X, Y) = (x, y);
public override string ToString() => $"({X}, {Y})";
}
3. Ref readonly return example
- ref return 上的 readonly 修飾符指示返回的引用無法修改。 下面的示例返回了一個對來源的引用牵祟。 它使用 readonly 修飾符來指示調(diào)用方無法修改來源:
private static readonly Point origin = new Point(0, 0);
public static ref readonly Point Origin => ref origin;
所返回的類型不需要為 readonly struct。 ref 能返回的任何類型都能由 ref readonly 返回诺苹。