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 写夏至的祝福语简短