Can two actions be combined in C #?

I just play with Actionto extract lambda expressions.

I have a boolean variable, and based on its value, my lambda body should be different.

However, in this particular case, the difference is simply a call to another method that does not change the type of the return value. This is what I have:

Action<MyType> myLambda;

if (myBooleanCondition)
{
     myLambda = x => x.ChangeBehavior();
}
else
{
     myLambda = x => x.ChangeBehavior().ChangeSize();
}

Is it possible to reduce / combine two lambda definitions into one to make it more elegant?

This project uses C # 4.0, but if it has been simplified in newer versions, let me know.

+4
source share
4 answers

+= , .

, :

Action<MyType> myLambda = x => x.ChangeBehavior();

if (!myBooleanCondition)
    myLambda += x => x.ChangeSize();

:

using System;

namespace Demo
{
    class MyType
    {
        public MyType ChangeBehavior()
        {
            Console.WriteLine("ChangeBehavior()");
            return this;
        }

        public void ChangeSize()
        {
            Console.WriteLine("ChangeSize()");
        }
    }

    class Program
    {
        static void Main()
        {
            var x = new MyType();

            test(true)(x);       // Calls ChangeBehavior()
            Console.WriteLine();
            test(false)(x);      // Calls ChangeBehavior() and then ChangeSize()
        }

        static Action<MyType> test(bool myBooleanCondition)
        {
            Action<MyType> myLambda = x => x.ChangeBehavior();

            if (!myBooleanCondition)
                myLambda += x => x.ChangeSize();

            return myLambda;
        }
    }
}

, , - . !

+7

, ( ): (?:)

Action<MyType> myLambda = myBooleanCondition ? x => x.ChangeBehavior() :
                                               x => x.ChangeBehavior().ChangeSize();
+5

else, ,

Func<MyType, MyType> ChangeBehavior, func;
func = ChangeBehavior = x => x.ChangeBehavior();

if (!myBooleanCondition)
    func = x => ChangeBehavior(x).ChangeSize();

Action<MyType> myLambda = x => func(x);
+2

. .

myBooleanCondition.

bool myBooleanCondition = false;

Action<MyType> myLambda = (x) => {
    if (myBooleanCondition)
    {
         x.ChangeBehavior();
    }
    else
    {
         x.ChangeBehavior().ChangeSize();
    }
};

.

Action<MyType, bool> myLambda = (x, condition) => {
    if (condition)
    {
         x.ChangeBehavior();
    }
    else
    {
         x.ChangeBehavior().ChangeSize();
    }
};

myType, myBooleanCondition.

bool myBooleanCondition = false;
MyType myType = new MyType();

Action myLambda = () => {
    if (myBooleanCondition)
    {
         myType.ChangeBehavior();
    }
    else
    {
         myType.ChangeBehavior().ChangeSize();
    }
};

.

+1

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


All Articles