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