如何解决C#9记录验证
使用C#9的新记录类型,如何在构造对象的过程中注入自定义参数验证 / null check /等,而无需重新编写整个构造函数?
类似的东西:
record Person(Guid Id,string FirstName,string LastName,int Age)
{
override void Validate()
{
if(FirstName == null)
throw new ArgumentException("Argument cannot be null.",nameof(FirstName));
if(LastName == null)
throw new ArgumentException("Argument cannot be null.",nameof(LastName));
if(Age < 0)
throw new ArgumentException("Argument cannot be negative.",nameof(Age));
}
}
解决方法
如果您可以不用位置构造函数,您可以在需要它的每个属性的 init
部分完成验证:
record Person
{
private readonly string _firstName;
private readonly string _lastName;
private readonly int _age;
public Guid Id { get; init; }
public string FirstName
{
get => _firstName;
init => _firstName = (value ?? throw new ArgumentException("Argument cannot be null.",nameof(value)));
}
public string LastName
{
get => _lastName;
init => _lastName = (value ?? throw new ArgumentException("Argument cannot be null.",nameof(value)));
}
public int Age
{
get => _age;
init =>
{
if (value < 0)
{
throw new ArgumentException("Argument cannot be negative.",nameof(value));
}
_age = value;
}
}
}
否则,您将需要创建一个自定义构造函数,如上面评论中所述。
(顺便说一句,请考虑使用 ArgumentNullException
和 ArgumentOutOfRangeException
而不是 ArgumentException
。这些继承自 ArgumentException
,但对于发生的错误类型更具体.)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。