C# - 嵌套 switch 语句



可以在外部 switch 语句的语句序列中包含一个 switch 语句。即使内部和外部 switch 语句的 case 常量包含公共值,也不会发生冲突。

语法

嵌套 switch 语句的语法如下所示:

switch(ch1) {
   case 'A':
   Console.WriteLine("This A is part of outer switch" );
   
   switch(ch2) {
      case 'A':
         Console.WriteLine("This A is part of inner switch" );
         break;
      case 'B': /* inner B case code */
   }
   break;
   case 'B': /* outer B case code */
}

示例

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         int a = 100;
         int b = 200;
         
         switch (a) {
            case 100: 
            Console.WriteLine("This is part of outer switch ");
            
            switch (b) {
               case 200:
               Console.WriteLine("This is part of inner switch ");
               break;
            }
            break;
         }
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.WriteLine("Exact value of b is : {0}", b);
         Console.ReadLine();
      }
   }
} 

编译并执行以上代码后,将产生以下结果:

This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
csharp_decision_making.htm
广告