C#FluentValidation用于类的层次结构

编程入门 行业动态 更新时间:2024-10-21 11:37:05
本文介绍了C#FluentValidation用于类的层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数据类层次结构

I have a hierarchy of data classes

public class Base { // Fields to be validated } public class Derived1 : Base { // More fields to be validated } public class Derived2 : Base { // More fields to be validated }

使用FluentValidation框架验证Derived1和Derived2而不复制基类字段的规则的合适方法是什么?

What would be the appropriate way to validated Derived1 and Derived2 using FluentValidation framework without duplicating rules for fields of Base class?

推荐答案

采取的一种方法如下:

public class Base { public string BaseName { get; set; } } public class Derived1 : Base { public string Derived1Name { get; set; } } public class BaseValidator<T> : AbstractValidator<T> where T : Base { public BaseValidator() { RuleFor(b => b.BaseName).NotNull(); } } public class Derived1Validator : BaseValidator<Derived1> { public Derived1Validator() { RuleFor(d => d.Derived1Name).NotNull(); } }

因此,您首先创建基本验证器,使其接受通用类型参数,并指定通用类型必须为base类型.为基类设置一般规则,然后继续.

So you first create your base validator, make it accept a generic type argument and specify that the generic type must be of type base. Set up your general rules for your base class and move on.

对于验证基类的子代的任何验证器,您都需要那些验证器从baseValidator继承,其中T将是您的派生类类型.

For any validators that validate children of your base class, you have those validators inherit from the baseValidator, where T will be your derived class type.

更多推荐

C#FluentValidation用于类的层次结构

本文发布于:2023-11-29 16:48:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:层次   结构   FluentValidation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!