Variable parameters in C# Lambda

前端 未结 5 1291
别跟我提以往
别跟我提以往 2021-01-01 23:07

Is it possible to have a C# lambda/delegate that can take a variable number of parameters that can be invoked with a Dynamic-invoke?

All my attempts to use the \'par

5条回答
  •  臣服心动
    2021-01-01 23:37

    The reason that it doesn't work when passing the arguments directly to DynamicInvoke() is because DynamicInvoke() expects an array of objects, one element for each parameter of the target method, and the compiler will interpret a single array as the params array to DynamicInvoke() instead of a single argument to the target method (unless you cast it as a single object).

    You can also call DynamicInvoke() by passing an array that contains the target method's parameters array. The outer array will be accepted as the argument for DynamicInvoke()'s single params parameter and the inner array will be accepted as the params array for the target method.

    delegate void ParamsDelegate(params object[] args);
    
    static void Main()
    {  
       ParamsDelegate paramsDelegate = x => Console.WriteLine(x.Length);
    
       paramsDelegate(1,2,3); //output: "3"
       paramsDelegate();      //output: "0"
    
       paramsDelegate.DynamicInvoke((object) new object[]{1,2,3}); //output: "3"
       paramsDelegate.DynamicInvoke((object) new object[]{}); //output: "0"
    
       paramsDelegate.DynamicInvoke(new []{new object[]{1,2,3}}); //output: "3"
       paramsDelegate.DynamicInvoke(new []{new object[]{}});      //output: "0"
    }
    

提交回复
热议问题