現在,你就擁有了 一個恆定類型。為了讓它有效的工作,你必須添加一個構造函數來完全初始化 address結構。這個address結構只須要額外的添加一個構造函數,來驗證每一個 字段。一個拷貝構造函數不是必須的,因為賦值運算符還算高效。記住,默認的 構造函數仍然是可訪問的。這是一個默認所有字符串為null,ZIP代碼為0的地址 結構:
public struct Address
{
private readonly string _line1;
private readonly string _line2;
private readonly string _city;
private readonly string _state;
private 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 );
}
// etc.
}
在使用這個恆定數據類型時,要求直接用不同的調用來一順的修 改它的狀態。你更寧願創建一個新的對象而不是去修改某個實例:
// Create an address:
Address a1 = new Address( "111 S. Main",
"", "Anytown", "IL", 61111 );
// To change, re-initialize:
a1 = new Address( a1.Line1,
a1.Line2, "Ann Arbor", "MI", 48103 );