将条件传递到Func<;bool>;Tuple<;字符串,字符串,Func<;bool>>;

本文关键字:gt lt bool 字符串 Func Tuple 条件 | 更新日期: 2023-09-27 17:59:25

我正在尝试创建一个元组列表,其中包含验证它们的属性和条件。所以我想到了这个想法:

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

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

将条件传递到Func<;bool>;Tuple<;字符串,字符串,Func<;bool>>;

像这样(使用lambda表达式):
var properties = new List<Tuple<string, string, Func<bool>>> 
{
    Tuple.Create<string, string, Func<bool>>(
                 FirstName, 
                 "User first name is required",
                 () => FirstName == null),
};

类似这样的东西:

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)),
};

请注意,lambda表达式的类型推理有一些限制。。。出于这个原因,使用了构建委托的CCD_ 1方式。

备选方案:

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),

最后你不得不在某个地方重复Func<bool>