只讀屬性

宣告

一個常見的誤解,特別是初學者,有隻讀屬性是用 readonly 關鍵字標記的屬性。這是不正確的,實際上以下是編譯時錯誤

public readonly string SomeProp { get; set; }

如果屬性只有一個 getter,則它是隻讀的。

public string SomeProp { get; }

使用只讀屬性建立不可變類

public Address
{
    public string ZipCode { get; }
    public string City { get; }
    public string StreetAddress { get; }

    public Address(
        string zipCode,
        string city,
        string streetAddress)
    {
        if (zipCode == null)
            throw new ArgumentNullException(nameof(zipCode));
        if (city == null)
            throw new ArgumentNullException(nameof(city));
        if (streetAddress == null)
            throw new ArgumentNullException(nameof(streetAddress));

        ZipCode = zipCode;
        City = city;
        StreetAddress = streetAddress;
    }
}