gpt4 book ai didi

c# - 复杂验证扩展

转载 作者:行者123 更新时间:2023-11-30 18:28:09 24 4
gpt4 key购买 nike

在为 Fluent Validation 规则构建器编写扩展时,我想到了进行更复杂的验证然后将其与客户端验证连接起来的想法。我已经成功创建了基于另一个属性验证一个属性的扩展,依此类推。我正在努力解决的是对多个字段的验证:

扩展方法如https://fluentvalidation.codeplex.com/wikipage?title=Custom&referringTitle=Documentation

public static IRuleBuilderOptions<T, TProperty> Required<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Action<MyRuleBuilder<T>> configurator)
{
MyRuleBuilder<T> builder = new MyRuleBuilder<T>();

configurator(builder);

return ruleBuilder.SetValidator(new MyValidator<T>(builder));
}

允许流畅添加规则的 MyRuleBuilder 类:

public class MyRuleBuilder<T>
{
public Dictionary<string, object> Rules = new Dictionary<string,object>();

public MyRuleBuilder<T> If(Expression<Func<T, object>> exp, object value)
{
Rules.Add(exp.GetMember().Name, value);

return this;
}
}

然后 View 模型和 View 模型验证器规则如下所示:

public class TestViewModel
{
public bool DeviceReadAccess { get; set; }
public string DeviceReadWriteAccess { get; set; }
public int DeviceEncrypted { get ; set; }
}

RuleFor(x => x.HasAgreedToTerms)
.Required(builder => builder
.If(x => x.DeviceReadAccess, true)
.If(x => x.DeviceReadWriteAccess, "yes")
.If(x => x.DeviceEncrypted, 1 ));

问题:

上面的代码工作正常,但我不喜欢的是“If”函数。它不强制该值属于选定的属性类型。示例:

RuleFor(x => x.HasAgreedToTerms)
.Required(builder => builder
.If(x => x.DeviceReadAccess, true) // I would like the value to be enforced to bool
.If(x => x.DeviceReadWriteAccess, "yes") // I would like the value to be enforced to string

// Ideally something like

// public MyRuleBuilder<T> If(Expression<Func<T, U>> exp, U value) but unfortunately U cannot be automatically inferred

这种架构是否可行,还是我应该采用不同的方法?

谢谢。

最佳答案

我认为您可以向该方法添加另一个通用参数U

public class MyRuleBuilder<T>
{
public Dictionary<string, object> Rules = new Dictionary<string, object>();

public MyRuleBuilder<T> If<U>(Expression<Func<T, U>> exp, U value)
{
Rules.Add(exp.GetMember().Name, value);

return this;
}
}

关于c# - 复杂验证扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25567356/

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