Overview
This is the seventh section of the book "Effective C #" reading notes. Through this article, I would like to tell you about a problem that we may not notice at ordinary times: Create a value type that is constant and atomic.
Starting from the type design
From class to struct
If we are going to design a type that stores the address of the recipient, we call this a type. It should contain such several attributes:
Province Province
City
Zip zip code
Require control of the ZIP format (must be all numbers, and 6-bit), how should we design it? I think a lot of people will write this:
public class Address {
private string province;
private string city;
private string zip;
public string Province {
get { return province; }
set { province = value; }
}
public string City {
get { return city; }
set { city = value; }
}
public string Zip {
get { return zip; }
set {
CheckZip(value); // 验证格式
zip = value;
}
}
// 检测是不是正确的 zip
private void CheckZip(string value) {
string pattern = @"d{6}";
if(!Regex.IsMatch(value, pattern))
throw new Exception("Zip is invalid! ");
}
public override string ToString() {
return String.Format("Province: {0}, City: {1}, Zip: {2}", province, city, zip);
}
}