jM2*_*.me 2 c# dictionary function
有人可以给我一个例子,说明我如何在字典中存储不同的函数,其中int作为键并作为值运行.那么我可以轻松地调用函数如下:
functionsDictionary[123](string);
Run Code Online (Sandbox Code Playgroud)
注意字典中的所有函数只需要一个输入字符串.并且不会有回报.
这听起来像你在追求
Dictionary<int, Action<string>>
Run Code Online (Sandbox Code Playgroud)
或者可能(根据你的头衔)
Dictionary<uint, Action<string>>
Run Code Online (Sandbox Code Playgroud)
样品:
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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3201 次 |
| 最近记录: |