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

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

问题描述

是否有可能有一个C#的lambda /代表,可以采取可变数目的可与动态调用?



我所有的尝试援引参数用在这方面已经失败了PARAMS关键字。






有工作代码的ANSWER

 委托无效美孚(PARAMS字符串[]字符串); 

静态无效的主要(字串[] args)
{
美孚X =字符串=>
{
的foreach(字符串s中的字符串)
Console.WriteLine(S);
};

//添加要清楚如何最终被用于:)
代表D = X;

d.DynamicInvoke(新[] {新的字符串[] {1,2,3}});
}


解决方案

这是它不的原因直接传递的参数时, DynamicInvoke() T的工作是因为 DynamicInvoke()预计对象的数组,一个元素目标方法的每个参数,编译器将演绎一个数组作为的 PARAMS 的阵列 DynamicInvoke(),而不是一个单一的参数目标方法(除非你施放它作为一个单一对象)。



您也可以拨打 DynamicInvoke()通过传递包含目标方法的参数数组的数组。外部阵列将被接受作为论据 DynamicInvoke()的单一的 PARAMS 的参数和内部阵列将被接纳为的 PARAMS 的阵列为目标的方法。

 委托无效ParamsDelegate(params对象[]参数)。 

静态无效的主要()
{
ParamsDelegate paramsDelegate = X => Console.WriteLine(x.Length);

paramsDelegate(1,2,3); //输出:3
paramsDelegate(); //输出:0

paramsDelegate.DynamicInvoke((对象)新的对象[] {1,2,3}); //输出:3
paramsDelegate.DynamicInvoke((对象)新的对象[] {}); //输出:0

paramsDelegate.DynamicInvoke(新[] {新的对象[] {1,2,3}}); //输出:3
paramsDelegate.DynamicInvoke(新[] {新的对象[] {}}); //输出:0
}


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 '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"}});
}

解决方案

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

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

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