在C#中宣告一個const陣列


在C#中,使用readonly宣告一個const陣列。

public static readonly string[] a = { "Car", "Motorbike", "Cab" };

在readonly中,與const不同,你可以在執行時設定值。

實現上述所見的另一種方法−

public ReadOnlyCollection<string> a { get { return new List<string> { "Car", "Motorbike", "Cab" }.AsReadOnly();}}

.NET framework 4.5對我們所看到的進行了改進−

public ReadOnlyCollection<string> a { get; } = new ReadOnlyCollection<string>(
new string[] { "Car", "Motorbike", "Cab" }
);

更新日期: 22-Jun-2020

10K+ 次觀看

開啟你的 職業

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.