0

我有以下代码引发空检查异常:

 RuleFor(x => x.TestString)
                .Must(x => !string.IsNullOrEmpty(x))
                .When(y => y.OtherArray!= null && y.OtherArray.Count > 0)
                .WithMessage("required") 
                .Must(x=> x.TestString.Equals("tiktok"))
                .WithMessage("Invalid") 

但是当 TestString 为 null 时,上面的代码会抛出 Object null 引用异常。

我的要求是当“OtherArray”有值时,“TestString”必须等于“tiktok”,此时应显示无效的TestString Invalid错误消息。

当“OtherArray”为空或为空时,无需检查“TestString”。有人可以帮忙吗?

4

1 回答 1

0

尝试这个:

RuleFor(x => x.TestString)
            .Must(x => !string.IsNullOrEmpty(x))
            .When(y => y.OtherArray!= null && y.OtherArray.Count > 0)
            .WithMessage("required") 
            .Must(x=> x.TestString != null && x.TestString.Equals("tiktok"))
            .WithMessage("Invalid") 
于 2021-08-13T14:41:30.197 回答