【问题标题】:Store Void Functions in a Dictionary [duplicate]将 Void 函数存储在字典中
【发布时间】:2019-02-08 08:42:51
【问题描述】:

我正在表单上创建一个输入文本框,并且我想要调用特定程序的特定命令,例如输入“时间”后,将返回一个显示当前时间的 MessageBox。

我目前使用案例,但希望直接从字典中调用函数

private void enter_button_Click(object sender, EventArgs e)
        {
            Dictionary<string, Int64> commandDict = new Dictionary<string, Int64>()
            {
                ["Do1"] = 1,
                ["Do2"] = 2,
                ["Do3"] = 3
            };
            long caseInput = 0;
            try
            {
                caseInput = Convert.ToInt64(commandDict[(textBox1.Text).ToLower()]); 
//Returns dict value as long integer /\
            }
            catch { }
            switch (caseInput)
            {
                case 1:
                    Console.WriteLine("Do Thing 1")
                    break;
                case 2:
                    Console.WriteLine("Do Thing 2")
                    break;
                case 3:
                    Console.WriteLine("Do Thing 3") 
                    break;
                default:
                    Console.WriteLine("Incorrect Input")
                    break;

我希望 case 1,2 和 3 是单独的函数(它们的功能已被淡化,但没有返回值,也没有输入参数)。我想要commandDict(我当前的字典,当文本“Do1”等输入到“textBox1.Text”时调用这3个程序。

【问题讨论】:

  • 链接副本上的 This answer 适用于 void 方法。

标签: c# function dictionary


【解决方案1】:

您可以使用如下代码。字典应该可以帮助你实现你想做的事情。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public class Test
{
    public static void Main(string[] args)
    {
        Dictionary<string, Action> dict = new Dictionary<string, Action>();
       dict.Add("Do1", ActionDo1);  
        dict.Add("Do2", ActionDo1); 

        dict["Do1"]();
    }

    public static void ActionDo1()
    {
        Console.WriteLine("The Do1 is called");
    }

    public static void ActionDo2()
    {
        Console.WriteLine("The Do2 is called");
    }


}

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    然后将您的字典声明为Dictionary&lt;string, Action&gt;,并将函数名称作为值添加到您的字典中。

    【讨论】:

      【解决方案3】:

      这边:

      class Program
      {
          private static Dictionary<string, Delegate> methods = new Dictionary<string, Delegate>();
          static void Main(string[] args)
          {
              methods.Add("Test1", new Action<string>(str => { Console.WriteLine(str); }));
              methods.Add("Test2", new Func<string, bool>(str => { return string.IsNullOrEmpty(str); }));
          }
      }
      

      您将能够将Action 添加到字典中,它相当于一个void 方法和Func,它可以接受输入和返回值。

      【讨论】:

        猜你喜欢
        • 2011-05-13
        • 2015-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-22
        • 2013-05-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多