找到你要的答案

Q:Passing a condition into Func of a Tuple

Q:通过条件为一元函数

I am trying to create a list of tuples with properties and conditions for their validation. So I had this idea in mind:

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

How can I pass expression of type (FirstName == null) as Func ?

我想创建一个列表,为验证和条件属性的元组。所以我心里有这个想法:

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

我怎样才能通过表达型(名字= = null)的Func?

answer1: 回答1:

Like this (using a 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),
};

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

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

Something like this:

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

Note that there are some limitatons to type inference for lambda expressions... for this reason the new Func<bool> way of building a delegate is used.

Alternatives:

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

In the end you have to repeate the Func<bool> somewhere.

像这样的东西:

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

请注意,有一些limitatons为lambda表达式的类型推断…为此,新功能& lt;布尔>;建造的方式使用委托。

选择:

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

你到底有没有重复的功能& lt;布尔>;的地方。

c#  properties  tuples