Execute lambda expression immediately after its definition?

后端 未结 5 1873
佛祖请我去吃肉
佛祖请我去吃肉 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:25

    Here's an example of how this might be used. You want to initialize a constructor with the result of a few lines of code that can't be written as a function because that is how the 3rd party API is structured.

    It is just glue code to prevent writing a standalone function that is never called anywhere else. I'm using Func instead of Action, but the answer is the same as user166390.

            // imagine several dozens of lines that look like this
            // where the result is the return value of a function call
            fields.Add(new ProbeField(){ 
                Command = "A",
                Field = "Average",
                Value = be.GetAverage()
            });
    
            // now you need something that can't be expressed as function call
            // so you wrap it in a lambda and immediately call it.
            fields.Add(new ProbeField(){ 
                Command = "C",
                Field = "Cal Coeff",
                Value = ((Func)(() => {
                    CalCoef coef;
                    Param param;
                    be.GetCalibrationCoefficients(out coef, out param);
                    return coef.lowDet1.ToString();
                }))()
            });
    

提交回复
热议问题