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 婆婆高寿祝福语大全简短