String- Function dictionary c# where functions have different arguments

后端 未结 9 2852
温柔的废话
温柔的废话 2021-02-19 09:13

Basically I\'m trying to make a string to function dictionary in c#, I\'ve seen it done like this:

Dictionary>
<         


        
9条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 09:40

    You can define your own delegate taking a params string[] argument, like this:

    delegate TOut ParamsFunc(params TIn[] args);
    

    And declares your dictionary like so:

    Dictionary> functions;
    

    So, you can use it like this:

    public static string Concat(string[] args)
    {
        return string.Concat(args);
    }
    
    var functions = new Dictionary>();
    functions.Add("concat", Concat);
    
    var concat = functions["concat"];
    
    Console.WriteLine(concat());                                //Output: ""
    Console.WriteLine(concat("A"));                             //Output: "A"
    Console.WriteLine(concat("A", "B"));                        //Output: "AB"
    Console.WriteLine(concat(new string[] { "A", "B", "C" }));  //Output: "ABC"
    

    Be aware that you still need to declare your methods with a string[] argument, even if you only need one string parameter.

    On the other hand, it can be called using params style (like concat() or concat("A", "B")).

提交回复
热议问题