I use delegates with lambda expressions instead of methods with just one line of code like:
Func<int, int, int> Add = (x, y) => x + y;
int Result = Add(1, 2); // 3
Now I have the problem that I need a unknown number of parameters. Is there a was to solve it like this:
Func<string, params string[], string> MergeFormat = (Look, values) => string.Format(Look, string.Join("-", values));
with params string[]
the result would be
string.Format(func, string.Join("-", v1, v2, v3)); //currently
MergeFormat(func, v1, v2, v3); //new
params
isn't part of the type itself, so you can't specify a Func<string, params string[], string>
. But you could declare your own delegates which are like Func
but which have a parameter array as the final parameter. For example:
using System;
delegate TResult ParamsFunc<T, TResult>(params T[] arg);
delegate TResult ParamsFunc<T1, T2, TResult>(T1 arg1, params T2[] arg2);
delegate TResult ParamsFunc<T1, T2, T3, TResult>(T1 arg1, T2 arg2, params T3[] arg3);
// etc
class Program
{
static void Main(string[] args)
{
ParamsFunc<string, string, string> func =
(format, values) => string.Format(format, string.Join("-", values));
string result = func("Look here: {0}", "a", "b", "c");
Console.WriteLine(result);
}
}
See more on this question at Stackoverflow