有人能为我提供一个示例,说明如何在字典中存储不同的函数,并将int作为键并作为值运行。那么我可以轻松地将函数调用如下:
functionsDictionary[123](string);
注意字典中的所有函数只接受一个字符串输入。并且没有回报。
答案 0 :(得分:8)
听起来像是在追求
Dictionary<int, Action<string>>
或可能(基于您的头衔)
Dictionary<uint, Action<string>>
样品:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
var dictionary = new Dictionary<int, Action<string>>
{
{ 5, x => Console.WriteLine("Action for 5: {0}", x) },
{ 13, x => Console.WriteLine("Unlucky for some: {0}", x) }
};
dictionary[5]("Woot");
dictionary[13]("Not really");
// You can add later easily too
dictionary.Add(10, x => Console.WriteLine("Ten {0}", x));
dictionary[15] = x => Console.WriteLine("Fifteen {0}", x);
// Method group conversions work too
dictionary.Add(0, MethodTakingString);
}
static void MethodTakingString(string x)
{
}
}
答案 1 :(得分:1)
Dictionary<int, Action<string>> _functions = new Dictionary<int, Action<string>>();
_functions[123]("hello");