将条件传递给元组的Func <bool> <string,string,=“”func <bool =“”>&gt;

时间:2015-06-23 14:00:58

标签: c# properties tuples

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

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?

传递

2 个答案:

答案 0 :(得分:9)

像这样(使用lambda expression):

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

答案 1 :(得分: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)),
};

请注意,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),

最后,您必须在某处重复Func<bool>