gpt4 book ai didi

c#-4.0 - 流畅的验证。继承验证类

转载 作者:行者123 更新时间:2023-12-03 11:38:56 25 4
gpt4 key购买 nike

我使用了 Fluent 验证器。但有时我需要创建一个规则层次结构。例如:

[Validator(typeof(UserValidation))]
public class UserViewModel
{
public string FirstName;
public string LastName;
}

public class UserValidation : AbstractValidator<UserViewModel>
{
public UserValidation()
{
this.RuleFor(x => x.FirstName).NotNull();
this.RuleFor(x => x.FirstName).NotEmpty();

this.RuleFor(x => x.LastName).NotNull();
this.RuleFor(x => x.LastName).NotEmpty();
}
}

public class RootViewModel : UserViewModel
{
public string MiddleName;
}

我想将验证规则从 UserValidation 继承到 RootValidation。但是这段代码不起作用:
public class RootViewModelValidation:UserValidation<RootViewModel>
{
public RootViewModelValidation()
{
this.RuleFor(x => x.MiddleName).NotNull();
this.RuleFor(x => x.MiddleName).NotEmpty();
}
}

如何使用 FluentValidation 继承验证类?

最佳答案

要解决此问题,您必须更改 UserValidation类到泛型。请参阅下面的代码。

public class UserValidation<T> : AbstractValidator<T> where T : UserViewModel
{
public UserValidation()
{
this.RuleFor(x => x.FirstName).NotNull();
this.RuleFor(x => x.FirstName).NotEmpty();

this.RuleFor(x => x.LastName).NotNull();
this.RuleFor(x => x.LastName).NotEmpty();
}
}

[Validator(typeof(UserValidation<UserViewModel>))]
public class UserViewModel
{
public string FirstName;
public string LastName;
}

public class RootViewModelValidation : UserValidation<RootViewModel>
{
public RootViewModelValidation()
{
this.RuleFor(x => x.MiddleName).NotNull();
this.RuleFor(x => x.MiddleName).NotEmpty();
}
}

[Validator(typeof(RootViewModelValidation))]
public class RootViewModel : UserViewModel
{
public string MiddleName;
}

关于c#-4.0 - 流畅的验证。继承验证类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4746390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com