在 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 框架 4.5 對上述實現了改進 −

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

更新時間:2020-06-22

10 千次以上瀏覽

開啟您的 職業生涯

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.