如何在.NET中创建特定于域的字符串类?

时间:2023-01-13 09:03:10

Given that in .NET the System.String class is sealed, how do you create a simple domain-specific string class so you can use type checking to ensure that the correct sort of string is used? Do you have a favourite implementation of such a class?

鉴于在.NET中System.String类是密封的,如何创建一个简单的特定于域的字符串类,以便您可以使用类型检查来确保使用正确的字符串类型?你有这样一个班级最喜欢的实现吗?

You might, for example, want to create a class to represent an email address to ensure that email is not accidentally sent to someone's postal address. Although that's not a great example I'm thinking about the cases where all you need is the type safety but no additional logic or validation.

例如,您可能希望创建一个表示电子邮件地址的类,以确保不会意外地将电子邮件发送到某人的邮政地址。虽然这不是一个很好的例子,但我正在考虑的情况是,你需要的只是类型安全,但没有额外的逻辑或验证。

2 个解决方案

#1


5  

You can wrap the string class in one of your own and add all the type checking you want.

您可以将字符串类包装在自己的类中,并添加所需的所有类型检查。

Think composition, instead of inheritance.

想想组合,而不是继承。

#2


0  

You might be interested in http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx in terms of your e-mail address example.

根据您的电子邮件地址示例,您可能对http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx感兴趣。

#1


5  

You can wrap the string class in one of your own and add all the type checking you want.

您可以将字符串类包装在自己的类中,并添加所需的所有类型检查。

Think composition, instead of inheritance.

想想组合,而不是继承。

#2


0  

You might be interested in http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx in terms of your e-mail address example.

根据您的电子邮件地址示例,您可能对http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx感兴趣。