C#只读属性
例子
宣言
一个常见的误解,尤其是初学者,有一个是只读属性是用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;
}
}
热门推荐
10 金婚祝福语大全简短唯美
11 惊喜自己的祝福语简短
12 退休后祝福语简短护士
13 儿童祝福语简短新春虎年
14 送心的祝福语简短
15 饭店国庆祝福语简短
16 孩子新年祝福语简短精辟
17 生日父亲祝福语 简短独特
18 客户祝福语事业文案简短