C# 仅当值不为null时,Fluent应用规则
在我前面的问题之后,我在我的C# 仅当值不为null时,Fluent应用规则,c#,.net,fluentvalidation,C#,.net,Fluentvalidation,在我前面的问题之后,我在我的事务类中有一个名为source的nullchar //source isnt required but when present must be 1 character 'I' or 'M' RuleFor(transaction => transaction.source.ToString()) .Matches("^[IM]?$") .When(t =&g
事务
类中有一个名为source
的null
char
//source isnt required but when present must be 1 character 'I' or 'M'
RuleFor(transaction => transaction.source.ToString())
.Matches("^[IM]?$")
.When(t => t.source.Value != null);
由于匹配
和当不可用于字符
时,我使用.ToString()
方法。但是,如果生成新的事务
对象时,源属性为null
,由于无法将null
源转换为字符串,应用程序失败
如果源代码不是null
,有人能建议一种仅对源代码运行验证的方法吗?我假设我编写的When表达式可以做到这一点,如果源代码为null
,那么验证过程的这一部分将被跳过,但它试图处理ToString()
验证的一部分不考虑,因此会导致错误。我不知道整个上下文,但我在这里看到了一个最明显的解决方案:
RuleFor(transaction => transaction.source != null ? transaction.source.ToString() : string.Empty)
.Matches("^[IM]?$")
匹配和当可用于char
数据类型时
我会建议像这样的
public class Transaction
{
public char? source { get; set; }
}
public class CustomerValidator : AbstractValidator<Transaction>
{
public CustomerValidator()
{
RuleFor(t => t.source)
.Must(IsValidSource);
}
private bool IsValidSource(char? source)
{
if (source == 'I' || source == 'M' || source == null)
return true;
return false;
}
}
公共类事务
{
公共字符?源{get;set;}
}
公共类CustomerValidator:AbstractValidator
{
公共CustomerValidator()
{
RuleFor(t=>t.source)
.Must(IsValidSource);
}
私有布尔IsValidSource(字符?源)
{
if(source='I'| | source='M'| | source==null)
返回true;
返回false;
}
}
我已编辑了您的标题。请不要在问题标题中包含关于所用语言的信息,除非没有它就没有意义。标签就是为了这个目的。同样,如果共识是“不,他们不应该”。