问题描述
|
我在C#中通过以下方式定义了几个变量:
public String firstName { get; set; }
public String lastName { get; set; }
public String organization { get; set; }
我想要的是在尝试设置值时向这些方法添加验证。假设您要为firstName设置一个值,则i应该通过正则表达式进行设置,否则将引发异常。是否可以使用这种“短语法”来构建,还是应该使用标准的(如JAVA中的)getter和setter并在那里验证数据?
解决方法
如果要验证设置属性的时间,则需要使用非自动属性(即,手动定义的
get
和set
方法)。
但是,另一种验证方法是使验证逻辑与域对象分离。
class Customer {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Organization { get; set; }
}
interface IValidator<T> {
bool Validate(T t);
}
class CustomerValidator : IValidator<Customer> {
public bool Validate(Customer t) {
// validation logic
}
}
然后,您可以说:
Customer customer = // populate customer
var validator = new CustomerValidator();
if(!validator.Validate(customer)) {
// head splode
}
这是我更喜欢的方法:
“ 5”不应对验证其自身数据负责,这是另一种责任,因此应居住在其他地方。
不同的情况要求针对同一域对象使用不同的验证逻辑。
,您现在拥有的称为“自动属性”,仅执行简单的“获取/设置”。为了自定义get
或set
的行为,您需要将属性转换为字段支持的属性:
private string _firstName;
public string FirstName
{
get {return _firstName;}
set
{
Validate(value); _firstName = value;
}
}
请注意,按照公认的C#命名最佳做法,我将ѭ9更改为ѭ10并大写了属性名称。
,我完全不会在ѭ11中添加验证。相反,我会创建一个名为validate
的函数...那样,您的所有验证代码都集中在一个位置上,而分散在整个setters
中。
,您必须为此使用完整属性语法。
,最佳实践是应用SRP。在单独的类中设置验证。
您可以使用FluentValidation
Install-Package FluentValidation
您可以通过继承AbstractValidator<Customer>
为Customer类定义一组验证规则:
例:
public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(x => x.Surname).NotEmpty();
RuleFor(x => x.Forename).NotEmpty().WithMessage(\"Please specify a first name\");
RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
RuleFor(x => x.Address).Length(20,250);
RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage(\"Please specify a valid postcode\");
}
private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
要运行验证器,请实例化验证器对象并调用Validate方法,并传入该对象进行验证。
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult result = validator.Validate(customer);
if(! results.IsValid) {
foreach(var failure in results.Errors) {
Console.WriteLine(\"Property \" + failure.PropertyName + \" failed validation. Error was: \" + failure.ErrorMessage);
}
}