关于IEquatable实现及Person类构造函数设计的技术咨询
First, let's restate the constructor code for clarity:
public Person(string lastName, string ssn) { if (Regex.IsMatch(ssn, @"\d{9}")) uniqueSsn = $"{ssn.Substring(0, 3)}-{ssn.Substring(3, 2)}-{ssn.Substring(5, 4)}"; else if (Regex.IsMatch(ssn, @"\d{3}-\d{2}-\d{4}")) uniqueSsn = ssn; else throw new FormatException("The social security number has an invalid format."); this.LastName = lastName; }
Now let's break down the key design choices here, especially relevant since you're exploring IEquatable<T>:
Enforce a Consistent SSN Format for Storage
The core goal here is standardization. By converting raw 9-digit SSNs to the hyphenatedXXX-XX-XXXXformat (and keeping valid hyphenated inputs as-is), the class ensuresuniqueSsnalways uses the exact same structure. This is a huge win forIEquatable<Person>implementations: when comparing twoPersonobjects for equality, you won't have to juggle different formats—you can do a direct string comparison ofuniqueSsn, which is simpler and far less error-prone. It also ensures consistent SSN display across your app, no matter how the input was originally provided.Offer Flexible, User-Friendly Input
This design reduces friction for anyone using thePersonclass. Users can pass SSNs in either of the two most common formats (plain 9 digits or hyphenated) without needing to pre-format the string themselves. You don't force callers to memorize a strict input rule, which makes the API more intuitive to use.Validate Early to Protect Data Integrity
The constructor immediately checks if the input SSN matches a valid pattern, and throws aFormatExceptionif it doesn't. This is defensive programming at work: it catches invalid data the moment aPersonobject is created, rather than letting bad SSN values spread through your code and cause hidden issues later—like failed database inserts, incorrect equality checks, or confusing display bugs. It guarantees everyPersoninstance you create has a valid, properly formatted SSN.
Since you're looking at IEquatable<T>, it's worth highlighting that this upfront standardization eliminates a big headache from your equality logic. Without it, you'd have to add extra normalization code inside your Equals method every time you compare instances—this constructor handles that work once, making your equality implementation cleaner and more reliable.
内容的提问来源于stack exchange,提问作者user13319447

