String - 函数字典c#其中函数具有不同的参数 [英] String- Function dictionary c# where functions have different arguments

查看:156
本文介绍了String - 函数字典c#其中函数具有不同的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我试图在c#中创建一个字符串来函数字典,我已经看到这样做:

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

Dictionary<string, Func<string, string>>

但问题是我要放入我的字典的函数有不同的参数数量不同种类。因此,如何制作这样的字典?

However the issue is that the functions I want to put into my dictionary all have different amounts of arguments of different types. Therefore how do I make a dictionary that will do this?

Adam

推荐答案

您可以使用 params string [] 参数定义自己的代理,如下所示:

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

delegate TOut ParamsFunc<TIn, TOut>(params TIn[] args);

并声明您的字典如下:

Dictionary<string, ParamsFunc<string, string>> functions;

所以,你可以这样使用:

So, you can use it like this:

public static string Concat(string[] args)
{
    return string.Concat(args);
}

var functions = new Dictionary<string, ParamsFunc<string, string>>();
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"

请注意,您仍然需要使用 string [] 参数,即使您只需要一个字符串参数。

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

另一方面,它可以使用 params style(如 concat() concat(A,B))。

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

这篇关于String - 函数字典c#其中函数具有不同的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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