Rob*_*hon 12 c# dictionary function
基本上我正在尝试在c#中创建一个字符串函数字典,我看到它是这样做的:
Dictionary<string, Func<string, string>>
Run Code Online (Sandbox Code Playgroud)
然而问题是我想要放入我的字典中的函数都有不同数量的不同类型的参数.因此,我如何制作一个能够做到这一点的字典呢?
亚当
Art*_*aca 11
您可以定义自己的委托参与params string[],如下所示:
delegate TOut ParamsFunc<TIn, TOut>(params TIn[] args);
Run Code Online (Sandbox Code Playgroud)
并声明你的字典:
Dictionary<string, ParamsFunc<string, string>> functions;
Run Code Online (Sandbox Code Playgroud)
所以,你可以像这样使用它:
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"
Run Code Online (Sandbox Code Playgroud)
请注意string[],即使只需要一个string参数,仍需要使用参数声明方法.
另一方面,它可以使用params样式(如concat()或concat("A", "B"))调用.
(已编辑)一种简单但令人讨厌的解决方案可能是这样的,
private void methodDictionary()
{
var infos = new Dictionary<string, MethodInfo>();
infos.Add("a", this.GetType().GetMethod("a"));
infos.Add("b", this.GetType().GetMethod("b"));
MethodInfo a = infos["a"];
a.Invoke(this, new[] { "a1", "b1" });
MethodInfo b = infos["b"];
b.Invoke(this, new object[] { 10, "b1", 2.056 });
}
public void a(string a, string b)
{
Console.WriteLine(a);
Console.WriteLine(b);
}
public void b(int a, string b, double c)
{
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8361 次 |
| 最近记录: |