【问题标题】:How do I include array positions in a switch-case statement?如何在 switch-case 语句中包含数组位置?
【发布时间】:2019-06-11 03:30:31
【问题描述】:

我需要将数组位置(如位置 [0]、位置 [1] 等)包含到开关盒中。

我是编程新手,我是从 C# 开始的,所以我尝试为这个 switch 语句创建一个非常简单的数组,但是我尝试过的所有方法都没有奏效。这是我目前所拥有的:

                string[] wordme = { "me", "myself", "i" };
                switch (wordme)
                {
                    case wordme[0]:
                        Me("me"); //refers to method
                        continue;
                    case wordme[1]:
                        Myself("myself"); //refers to method
                        continue;
                    case wordme[2]:
                        I("i");//refers to method
                        continue;
                    default:
                        continue;

                }

我希望它引用这些方法,但由于 3 条错误消息而无法运行,所有错误消息都指“case”行,内容为“无法将类型 'string' 隐式转换为 'string[]'”

【问题讨论】:

  • 你到底想做什么?您是否想从某个地方读取一个单词,然后根据它是否是数组中的任何单词进行切换?

标签: c# arrays switch-statement


【解决方案1】:

我不完全确定你想要做什么,或者你为什么需要这样做。但是,您可以使用when contextual keyword

从 C# 7.0 开始,case 标签不再需要相互 排他性,以及 case 标签出现在 switch 中的顺序 语句可以确定执行哪个 switch 块。当关键字 可用于指定导致其关联的过滤条件 只有当过滤条件也为真时,case 标签才为真

string[] wordme = { "me", "myself", "i" };

for (int i = 0; i < wordme.Length; i++)
{
   switch (wordme[i])
   {
      case "me" when i == 0:
         Me("me"); //refers to method
         break;
      case "myself" when i == 1:
         Myself("myself"); //refers to method
         break;
      case "i" when i == 2:
         I("i"); //refers to method
         break;
      default:
         break;

   }
}

或者另一种猜测

string[] wordme = { "me", "myself", "i" };

var mapping = new Dictionary<(string key, int ID), Action<string>> { 
       {("me", 0), s => Me(s)},
       {("myself", 1), s => Myself(s)},
       {("i", 2), s => I(s) }};

for (var i = 0; i < wordme.Length; i++)
   if (mapping.TryGetValue((wordme[i], i), out var action))
      action(wordme[i]);

【讨论】:

  • 我也不知道 OP 想要做什么,但我非常怀疑这是你发布的内容......
  • @KenY-N,是的,这个问题是一个神秘的奇迹,尽管我的假设是它的某种顺序解析器(猜测)
【解决方案2】:

请检查这里! foreach (var item in wordme)Console.WriteLine(item);

【讨论】:

    猜你喜欢
    • 2011-08-15
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多