[英]Checking case in multiple case statement
Consider following case statement 考虑以下案例陈述
Case 'A':
break;
Case 'B':
Case 'C':
// some logic
int i = 0;
// here I need i =5 (if case id 'B') and i=10 (if case is 'C')
// Rest of the logic is same
break;
I know I can achieve this by writing seperate case for 'B' and 'C' and writing rest of the logic in a seperate function and call that function in 'B' and 'C' case. 我知道我可以通过为'B'和'C'编写单独的大小写并在单独的函数中编写其余逻辑,然后在'B'和'C'的情况下调用该函数来实现。
But is there any way, I can check the case in Case statement only ... as follows 但是有什么办法,我只能检查Case语句中的大小写...如下
Case 'B':
Case 'C':
// Can I check here
// if (case == 'B')
// i = 5;
// if (case == 'C')
// i = 10;
// Rest of the logic
I tried the following which worked without any problems: 我尝试了以下有效的方法:
switch (a)
{
case 'A':
Console.WriteLine("Es ist ein 'A'.");
break;
case 'B':
case 'C':
if (a == 'B')
Console.WriteLine("Es ist ein 'B'.");
if (a == 'C')
Console.WriteLine("Es ist ein 'C'.");
break;
}
But if you're just checking if it's 'B' or 'C', I would suggest writing two separate cases. 但是,如果您只是检查它是“ B”还是“ C”,我建议编写两个单独的案例。
Put your //Rest of Logic
inside a new method, and do separate test cases for a neater code: 将//Rest of Logic
放到新方法中,并为更整洁的代码做单独的测试用例:
private void DoSomething(int i)
{
//Rest of Logic
}
public void SwitchMethod(char input)
{
int i = 0;
Switch (input)
{
case 'A':
break;
case 'B':
i = 5;
DoSomething(i);
break;
case 'C':
i = 10;
DoSomething(i);
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.