只读属性

声明

一个常见的误解,特别是初学者,有只读属性是用 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;
    }
}