【问题标题】:How can I compare a users input to a list of methods?如何将用户输入与方法列表进行比较?
【发布时间】:2022-11-01 19:45:58
【问题描述】:

我正在编写一些代码,其中我制作了一些方法并将它们全部放在一个列表中,但是我希望用户能够从列表中选择一个方法,然后运行该方法,因为我不希望所有方法都运行并仅输出所选方法的答案,因为这是低效的。

class program
    {
        //arrays
        static void Arrays()
        {
            Console.WriteLine("Enter number of cars:");
            Console.ReadKey();
        }

        // List
        static void List()
        {
            Console.WriteLine("Enter items for shopping list");
            shoppingList.Add("Apples");
            shoppingList.Add("oranges");
            shoppingList.Add("milk");
            shoppingList.Add("butter");

            Console.ReadKey();
        }

        static void Main(string[] strings)
        {
            List<Action> methods = new List<Action>();

            methods.Add(Arrays);
            methods.Add(List);

            Console.WriteLine("what method do you want:");
            string answer = Console.ReadLine();

            foreach (Action a in methods.Where(//one of the methods == answer));
                Console.WriteLine(//the method that is == answer);

            if (answer == //one methods in list)
            { 
                Console.WriteLine(////the method that is == answer);   
            }
        }
 

【问题讨论】:

  • 您可以在代码块中发布您目前拥有的内容吗?我很难想象
  • 创建一个字典,名称(字符串)作为键,函数/委托作为值。或者,您可以使用枚举作为数组的索引并将字符串映射到枚举。
  • 我只是想创建一个程序,用户可以在其中选择他们想要运行的方法,目前只有 2 个,他们会做一些他们不太重要的事情,并且与答案相同的方法意味着它将运行方法是用户选择

标签: c#


【解决方案1】:

您可以使用字典:

Dictionary<string, Action> methods = new(StringComparer.OrdinalIgnoreCase);
methods.Add(nameof(Arrays), Arrays);
methods.Add(nameof(List), List);

Console.WriteLine("what method do you want:");
string answer = Console.ReadLine();
if(methods.TryGetValue(answer, out Action doIt))
{
    doIt();
}

【讨论】:

  • @Coder175 别介意友好的评论,但说“谢谢,这有帮助”的规范方式是投票并接受(单击复选标记)答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多