C# 使用FluentValidation将lambda表达式作为方法参数传递

C# 使用FluentValidation将lambda表达式作为方法参数传递,c#,lambda,fluentvalidation,C#,Lambda,Fluentvalidation,我正在利用FluentValidation对我的程序进行一些服务器端验证。为了使用一些自定义验证,我使用了must验证程序,它允许您传入谓词并返回bool来测试验证是否成功。我尝试的验证包括检查数组中是否存在字符串 但是,这些细节在很大程度上是不相关的,因为我需要能够将谓词与第二个字符串[]变量一起传递到方法中 以下是我的验证方法: public bool StringInArray(Func<string> predicate, string[] testArray)

我正在利用FluentValidation对我的程序进行一些服务器端验证。为了使用一些自定义验证,我使用了
must
验证程序,它允许您传入谓词并返回bool来测试验证是否成功。我尝试的验证包括检查数组中是否存在字符串

但是,这些细节在很大程度上是不相关的,因为我需要能够将谓词与第二个
字符串[]
变量一起传递到方法中

以下是我的验证方法:

public bool StringInArray(Func<string> predicate, string[] testArray)
        {
            if(testArray.Contains(predicate.Invoke()))
            {
                return true;
            }

            return false;
        }
funderStrings
是我正在检查的who内容的数组
p.Funder
是我在数组内部检查的字符串

p=>p
参数不正确,我得到一个
委托'Func'不接受1个参数的编译错误。我不确定应该如何将字符串传递到
StringInArray
方法中。

您想要这样:

    public bool StringInArray(Func<string, string> conversion, string[] testArray)
    {
        if (testArray.Any((s) => s.Equals(conversion(s))))
        {
            return true;
        }

        return false;
    }
    ...
    RuleFor(p => p.Funder).Must(() => StringInArray(p => p, funderStrings));
public bool StringInArray(Func转换,字符串[]testArray)
{
如果(testArray.Any((s)=>s.Equals(转换)))
{
返回true;
}
返回false;
}
...
规则(p=>p.Funder)。必须(()=>StringInArray(p=>p,funderStrings));
或者这个:

    public Func<bool> StringInArray(string s, string[] testArray)
    {
        return () => testArray.Contains(s);
    }
    ...
    RuleFor(p => p.Funder).Must(() => StringInArray(p => p, funderStrings));
public Func StringInArray(字符串s,字符串[]testArray)
{
return()=>testArray.Contains;
}
...
规则(p=>p.Funder)。必须(()=>StringInArray(p=>p,funderStrings));

请进一步详细说明您确切期望
StringInArray
方法做什么,
必须
方法接收和执行

这应该如何工作?StringInArray方法应该做什么?您调用
testArray.Contains(string)
,其结果本质上是
string myMethod()
。我需要能够测试数组中是否存在字符串。问题是我不能简单地从
.Must
方法传递字符串,因为它要求通过谓词访问字符串。因此,我需要将包含我的测试字符串的谓词传递到
StringInArray
方法中,并能够在方法内部访问它。但实际操作的方式是,传递StringInArray的结果(它是bool,不是谓词)和StringInArray的内部,我的评论适用问题在于
p=>p
是Func的签名,因为它接受一个参数(p)并返回一个值(也是p)。Func(即不接受参数并生成字符串的函数)不能接受参数,因此会出现错误。
    public Func<bool> StringInArray(string s, string[] testArray)
    {
        return () => testArray.Contains(s);
    }
    ...
    RuleFor(p => p.Funder).Must(() => StringInArray(p => p, funderStrings));