Execute lambda expression immediately after its definition?

后端 未结 5 1841
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 17:56

Is there a way to execute a lambda expression immediately after its definition?

In other words (Invalid C# code):



        
5条回答
  •  心在旅途
    2021-01-03 18:31

    For my own projects I've sometimes written a tiny reusable helper function to make the syntax for an immediately invoked lambda look shorter. This 'Inv' was inspired by the similar 'fun' function in the LanguageExt library.

    // Helper utility functions
    public static void Inv(Action a) => a();
    public static T Inv(Func f) => f();
    
    private static void TestMethod()
    {
        // Action example
        Inv(() => Console.WriteLine("Hello World!"));
        // Func example with no parameters
        bool result = Inv(() =>
        {
            if (1 == 1)
                return true;
            else
                return false;
        });
    }
    

    You could also extend this with a few other overloads to make it so you could pass in parameters, but these look a bit more cumbersome syntax wise and may not be as helpful.

    public static Func Inv(Func f) => f;
    public static Func Inv(Func f) => f;
    
    string printNumber = Inv((int number) => $"This is the number {number}")(5);
    int addedNumbers = Inv((int x, int y) => x + y)(5, 6);
    

提交回复
热议问题