【发布时间】:2021-12-03 15:31:02
【问题描述】:
【问题讨论】:
-
创建Base Class 是我看到的一种解决方法
标签: c# .net-core fluentvalidation
【问题讨论】:
标签: c# .net-core fluentvalidation
我认为如果存在这样的机会,他们会在文档中提到它,但正如您所见,他们没有。在我看来,添加这样的工具并不是一个好主意,因为在所有具有特定类型的验证器实例之间共享验证规则可能会导致意外的验证结果。这也意味着您必须制作一个可以从全局上下文中排除特定验证器的工具。因此,将编辑单个 .cs 文件与您的具体类型的验证器进行比较,不要害怕破坏其他人的验证逻辑,以使用使您的代码更不可靠、更难以理解和维护的东西。还值得吗?
但是,如果您确定可以在验证器之间共享验证规则,那么您可以使用基类来存储这些规则(正如您在 cmets 中提到的那样)。
例子:
public class Parent
{
public string ParentValue1 { get; set; }
public string ParentValue2 { get; set; }
}
public class Child : Parent
{
}
和验证器:
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(x => x.ParentValue1).NotEmpty();
RuleFor(x => x.ParentValue2).NotEmpty();
}
}
public class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
Include(new ParentValidator());
}
}
【讨论】: