C#에서는 다른 switch 문 안에 하나의 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 */
} 다음은 C#의 중첩된 switch 문의 예입니다.
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;
} 전체 예를 살펴보겠습니다.
예
using System;
namespace Demo {
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