将条件传递给元组<string,string,Func <bool >>的Func <bool>

eYe*_*eYe 6 c# tuples properties

我正在尝试创建一个元组列表,其中包含用于验证的属性和条件.所以我有这个想法:

List<Tuple<string, string, Func<bool>>> properties = new List<Tuple<string, 
                                                                    string,
                                                                    Func<bool>>> 
{
    Tuple.Create(FirstName, "User first name is required", ???),
};
...
Run Code Online (Sandbox Code Playgroud)

如何将类型(FirstName == null)的表达式作为Func传递?

Yuv*_*kov 9

像这样(使用lambda表达式):

var properties = new List<Tuple<string, string, Func<bool>>> 
{
    Tuple.Create<string, string, Func<bool>>(
                 FirstName, 
                 "User first name is required",
                 () => FirstName == null),
};
Run Code Online (Sandbox Code Playgroud)


xan*_*tos 6

像这样的东西:

List<Tuple<string, string, Func<bool>>> properties = new List<Tuple<string, string, Func<bool>>> 
{
    Tuple.Create(FirstName, "User first name is required", new Func<bool>(() => FirstName == null)),
};
Run Code Online (Sandbox Code Playgroud)

请注意,lambda表达式的类型推断存在一些限制......因此new Func<bool>,使用构建委托的方式.

备择方案:

Tuple.Create(FirstName, "User first name is required", (Func<bool>)(() => FirstName == null)),
Tuple.Create<string, string, Func<bool>>(FirstName, "User first name is required", () => FirstName == null),
new Tuple<string, string, Func<bool>>(FirstName, "User first name is required", () => FirstName == null),
Run Code Online (Sandbox Code Playgroud)

最后你必须重复Func<bool>某个地方.