a { get { return new">

在 C# 中声明 const 数组

来源:这里教程网 时间:2026-02-21 16:22:45 作者:

在 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" }
);

相关推荐