Variable parameters in C# Lambda

前端 未结 5 1278
别跟我提以往
别跟我提以往 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:36

    I feel like there's a very crucial point that isn't being discussed here, and that's that if you've defined a delegate type that takes a params argument, there's very little point to calling DynamicInvoke on it at all. The only scenario I can imagine in which this would come into play is if you have a delegate of your custom type and you are passing it as a parameter to some method that accepts a Delegate argument and calls DynamicInvoke on that.

    But let's look at this code in the OP's update:

    delegate void Foo(params string[] strings);
    
    static void Main(string[] args)                       
    {
        Foo x = strings =>
        {
            foreach(string s in strings)
                Console.WriteLine(s);
        };
    
        x.DynamicInvoke(new[]{new string[]{"1", "2", "3"}});
    }
    

    The DynamicInvoke call above is totally superfluous. It would be much more sensible for that last line to read:

    x("1", "2", "3");
    

提交回复
热议问题