Use Func <T, bool> [] as a parameter list and check the result for each function

UPDATED: I am trying to write a method to do something work, and before it actually does the work, it has to go through some checks. These checks depend on what kind of work he is going to do.

After some thoughts, I still want to use the same templates with some minor changes.  Now I want to do the following code:

SomeClass:

        public SomeResponse DoSomething<T>(params Func<T, bool>[] validations)
        {
            if(validations.All(v=>v(T))
            {
                some logic..
            }
            return SomeResponse;
        }

Using:

       private Func<SomeRequest, bool> ValidateName = r =>
        {return !string.IsNullOrWhiteSpace(r.Name);};
       private Func<SomeRequest, bool> ValidatePhone = r =>
        {return !string.IsNullOrWhiteSpace(r.Phone);};

       var someResponse = SomeClass.DoSomething<SomeRequest>(ValidateName,ValidatePhone);

Again, the code is currently not working because it gives me an error on

if(validations.All(v=>v(T))

In principle, the Type parameter is invalid here, and I could not find a way to pass the actual object SomeRequestto Func.

, , , true, , Type

:

, , :

:

SomeClass:

    public SomeResponse DoSomething<T>(T request, params Func<T, bool>[] validations)
    {
        if(validations.All(v=>v(request))
        {
            some logic..
        }
        return SomeResponse;
    }

:

var someResponse = SomeClass.DoSomething<SomeRequest>(someRequest, ValidateName,ValidatePhone);

, , .

+4
3

!

, Validations - Func<Request, bool>, , Request bool.

, bool Func, Request. # Func , . , LINQ :

validations.All(f => f(request))

true , Validations true ( Request).

, if :

// I'm just guessing what the code to make a Request object will look like
Request request = resource.GetRequest();

if (!validations.All(f => f(request)))
{
    throw new Exception("Not all of the validations checked out");
}

, , Request, , .

+9

, , , - :

if (Validations.All(v => v(resource)))
0

params, . Func .

public void DoSomething(Resource resource, Func<Request, bool>[] Validations)

LINQ All, , .

if (Validations.All(v => v(resource)))
0
source

Source: https://habr.com/ru/post/1611491/


All Articles