0

我有一个包含地址字段的客户类。根据我的研究,我可以使用属性:

public class Customer{
   //...
   [Required]
   public Address CustomerAddress { get; set; }
} 

或其他方式:

public class AddressSettings{
   public bool AddressRequired { get; set; }
   //...other settings
}

两种方式都是有效的方法吗?如果不是,为什么另一种方式更好?

4

2 回答 2

2

在我看来,使用属性更好更专业,使用属性更易读、更灵活、更容易管理,并且有很多开箱即用的特性

于 2013-09-07T05:11:49.153 回答
1

对于基本验证,最好使用 DataAnnotations。

另一种选择是FluentValidation(我强烈推荐)

您可以有一个单独的类进行验证,但仍然与您的视图模型属性具有强类型关联

[Validator(typeof(PersonValidator))]
public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Name).Length(0, 10);
        RuleFor(x => x.Email).EmailAddress();
        RuleFor(x => x.Age).InclusiveBetween(18, 60);
    }
}

使用这种方法,您可以拥有更复杂和丰富的验证逻辑。

于 2013-09-07T05:36:20.947 回答