public readonly struct Address
{
public readonly string Line1;
public readonly string Line2;
public readonly string City;
public readonly string State;
public readonly int ZipCode;
public Address(string line1, string line2, string city, string state, int zipCode)
{
Line1 = line1;
Line2 = line2;
City = city;
State = state;
ZipCode = zipCode;
ValidateState(state);
ValidateZip(zipCode);
}
private static void ValidateState(string state) { /* ... */ }
private static void ValidateZip(int zip) { /* ... */ }
}
// 建立
Address a1 = new Address("111 S. Main", "", "Anytown", "IL", 61111);
// 修改城市 → 建立新實例
a1 = new Address(a1.Line1, a1.Line2, "Ann Arbor", "MI", 48103);
readonly,建構函式後不可修改set 存取器,僅保留 get避免了「修改一個欄位導致物件暫態無效」的問題。物件一生要么是有效初始值,要么是經驗證的新值,不存在中間狀態。