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 values that are declared within a function when the function is called are known as an argument. The variables that are defined when the function is declared are known as parameters. 2. These are used in function call statements to send value from the calling function to the receiving function.
Parameter list. The list of formal parameters being passed onto the function. In this case, there are two parameters of type int passed to the function.
Here we use macros to implement the functionality of variable arguments. Use va_list type variable in the function definition. Use int parameter and va_start macro to initialize the va_list variable to an argument list.
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"
}
No, but any of the parameters it does take can be an array.
Without more details, that's the long and short of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With