如何在switch-case语句中包含数组位置?

时间:2019-06-11 03:30:31

标签: c# arrays switch-statement

我需要在开关盒中包含数组位置,例如位置[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 []'”

2 个答案:

答案 0 :(得分:2)

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

  

从C#7.0开始,案例标签不再需要相互   排他性,以及标签在开关中出现的顺序   语句可以确定执行哪个切换块。 when关键字   可用于指定导致其关联的过滤条件   仅当过滤条件也为真时,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]);

答案 1 :(得分:0)

请以这种方式检查! foreach(wordme中的可变项)Console.WriteLine(item);

相关问题