【问题标题】:C# Is it possible to run a function with only a string? [closed]C# 是否可以仅使用字符串运行函数? [关闭]
【发布时间】:2020-01-16 15:20:54
【问题描述】:

对不起,这是一个愚蠢的问题。所以我让自己成为一名私人助理。我有一组命令,每个命令都有一个函数。如果用户输入命令,我如何让它去运行函数?

【问题讨论】:

  • 你能展示一些你的代码吗?你在用字典吗?你听说过代表吗?

标签: c# function command


【解决方案1】:

让我们将一些命令定义为没有返回值的 void 方法。

private void DoCommand1() {
    Console.WriteLine("executing command 1");
}

private void DoCommand2() {
    Console.WriteLine("executing command 2");
}

您可以使用字典将字符串映射到函数:

var commands = new Dictionary<string, Action>();
commands.Add("command1", () => DoCommand1());
commands.Add("command2", () => DoCommand2());

然后从字符串运行命令:

string myCommand = "command2";
commands[myCommand].Invoke(); //will print "executing command 2"

您应该看看 C# 中的 delegatesAction Delegates

【讨论】:

    【解决方案2】:

    您想制作一些强类型输入并在 C# 中处理这些输入。这是如何完成的。

    使用您想要强输入的所有命令(例如 Login、Logout)创建一个 Enum。

    制作一本字典

    private readonly Dictionary<string, StronglyTypedCommands> localBotCommands = new Dictionary<string, StronglyTypedCommands>();
    

    为您将获得的输入和命令类型存储一些静态字符串。

    在该方法中,您可以借助此字典找出确切的输入内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 2015-02-26
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2011-12-21
      • 2021-11-06
      相关资源
      最近更新 更多