Passing params through a Func<>

徘徊边缘 提交于 2019-12-24 00:55:29

问题


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

回答1:


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



回答2:


You can't do it this way, but there is a workaround solution that you could use:

If you define your Func this way:

Func<string[], string> FuncArray = (listOfStrings) => 
{
    // Here you can work on the listOfStrings, process it... 
    // and finaly you return a string from this method... 
}

Then you can later use that FuncArray in other calls this way:

public void MyMethod(Func<string[], string> delegateMethod, params string[] listOfString)
{
    if (delegateMethod != null)
    {
        string value = delegateMethod(listOfStrings);
    }

}

So you simply define a Func<> that takes an array of strings as a parameter, and then you can call that Func<> from another method which has a "params string[]" parameter.



来源:https://stackoverflow.com/questions/27565950/passing-params-through-a-func

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!