Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khai báo mảng hằng (const array) trong C#

C# không cho phép const cho mảng (reference type). Dùng readonly hoặc ReadOnlyCollection<T>.

Cách 1: readonly field (khuyến nghị)

public static readonly string[] Colors = { "Red", "Green", "Blue" };

// Khởi tạo tại runtime (constructor)
public class Config
{
    public static readonly string[] AllowedExtensions;
    
    static Config()
    {
        AllowedExtensions = LoadFromConfig(); // Có thể gán tại runtime
    }
}

Cách 2: ReadOnlyCollection<T> (bảo vệ nội dung)

using System.Collections.ObjectModel;

public class Settings
{
    private static readonly List _items = new List { "A", "B", "C" };
    
    // Property chỉ đọc, trả về wrapper readonly
    public static ReadOnlyCollection Items 
        => new ReadOnlyCollection(_items);
    
    // C# 6+ expression-bodied property
    // public static ReadOnlyCollection Items { get; } 
    //     = new ReadOnlyCollection(new[] { "A", "B", "C" });
}

Cách 3: ImmutableArray (System.Collections.Immutable)

using System.Collections.Immutable;

public static readonly ImmutableArray Constants 
    = ImmutableArray.Create("A", "B", "C");

So sánh

CáchBảo vệ tham chiếuBảo vệ nội dungKhởi tạo runtime
readonly arrayCóKhông (vẫn sửa được element)Có
ReadOnlyCollectionCóCó (interface chỉ đọc)Có
ImmutableArrayCóCó (struct bất biến)Có

Khuyến nghị: Dùng ImmutableArray cho .NET Core/.NET 5+, ReadOnlyCollection cho .NET Framework.