C# Lambda 中的可变参数 [英] Variable parameters in C# Lambda

查看:26
本文介绍了C# Lambda 中的可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能有一个 C# lambda/delegate 可以接受可变数量的参数,这些参数可以通过动态调用进行调用?

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?

我在此上下文中使用params"关键字的所有尝试都失败了.

All my attempts to use the 'params' keyword in this context have failed.

使用来自答案的工作代码更新:

UPDATE WITH WORKING CODE FROM ANSWER:

delegate void Foo(params string[] strings);

static void Main(string[] args)                       
{
    Foo x = strings =>
    {
        foreach(string s in strings)
            Console.WriteLine(s);
    };

    //Added to make it clear how this eventually is used :)
    Delegate d = x;

    d.DynamicInvoke(new[]{new string[]{"1", "2", "3"}});
}

推荐答案

直接将参数传递给 DynamicInvoke() 的原因是因为 DynamicInvoke() 需要一个对象数组,目标方法的每个参数一个元素,编译器会将单个数组解释为 params 数组到 DynamicInvoke()目标方法的单个参数(除非您将其转换为单个 object).

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).

您还可以通过传递包含目标方法的参数数组的数组来调用 DynamicInvoke().外部数组将被接受为 DynamicInvoke() 的单个 params 参数的参数,内部数组将被接受为 params 数组为目标方法.

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"
}

这篇关于C# Lambda 中的可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆