我在下面有这个基类:
abstract class RequiredString {
protected readonly string _text;
public RequiredString(string name, string text)
{
if (string.IsNullOrWhiteSpace(text))
throw new TextEmptyException($"The '{name}' field is required");
_text = text;
}
public RequiredString(string name, string text, int maxLength): this(name, text)
{
if (_text.Length > maxLength)
throw new TextLengthTooLongException($"The '{name}' field length is too long ({text.Length}/{maxLength})");
}
public static implicit operator string(RequiredString field)
{
return field._text;
}
}
我有一打继承自基类的类。全部具有最大长度: 例如:
public sealed class Email : RequiredString
{
private const int Length = 255;
private const string Name = "Email";
public Email(string text) : base(Name, text, Length)
{
try
{
new MailAddress(_text);
}
catch (FormatException ex)
{
throw new EmailFormatException($"'{_text}' field is not a valid email string", ex);
}
}
public static implicit operator Email(string text)
{
return new Email(text);
}
}
比方说,读者检查了Email类,但没有看到基类。
他/她是否清楚长度检查在基类中进行? 是有意义的还是应该在每个继承的类中进行长度检查? 您将如何重构该代码以使其更简洁?
谢谢!