【问题标题】:How to store functions in Dictionary with uint as key (C#)如何以 uint 为键将函数存储在字典中(C#)
【发布时间】:2011-02-26 07:43:54
【问题描述】:

谁能给我一个例子,说明我如何在字典中存储不同的函数,其中 int 作为键,函数作为值。那么我可以很容易地调用如下函数:

functionsDictionary[123](string);

注意字典中的所有函数都只接受一个字符串输入。而且不会有回报。

【问题讨论】:

标签: c# function dictionary


【解决方案1】:

听起来你在追求

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)
    {
    }
}

【讨论】:

  • 用dictionary.Add()添加函数怎么样?
  • @user621033:编辑了我的答案以举一个例子。
  • 添加已经存在的函数名怎么样pastebin.com/TYfs2u1x
  • @user621033:您的登录方法不接受字符串,因此您不能这样添加。但是,我已经编辑了我的答案,以提供方法组转换的示例。
  • 这就是我错过的。谢谢:)
【解决方案2】:
Dictionary<int, Action<string>> _functions = new Dictionary<int, Action<string>>();
_functions[123]("hello");

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 2019-08-12
    • 2020-06-07
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多