c# switch
The switch statement in C# is used to execute a block of code based on different cases. It evaluates an expression and compares it with the values specified in the case statements. If a match is found, the corresponding block of code associated with that case is executed.
Here is an example of how to use the switch statement in C#:
int num = 2;
switch (num)
{
case 1:
Console.WriteLine("Number is 1");
break;
case 2:
Console.WriteLine("Number is 2");
break;
case 3:
Console.WriteLine("Number is 3");
break;
default:
Console.WriteLine("Number is not 1, 2, or 3");
break;
}
In this example, the variable num is evaluated against the cases specified in the switch statement. Since num has a value of 2, the code block associated with the case 2 is executed, which prints "Number is 2" to the console.
If none of the cases match the value of the expression, the code block associated with the default case is executed. In this example, if num had a value other than 1, 2, or 3, the message "Number is not 1, 2, or 3" would be printed. The break statement is used to exit the switch statement once a matching case is found
原文地址: http://www.cveoy.top/t/topic/i0HW 著作权归作者所有。请勿转载和采集!