[英]Switch case or if else
I have this long loop of if..else. 我有一个漫长的if..else循环。 Can anybody help me in knowing if "switch case" is better for this or "if..else"?
有人可以帮助我知道“ switch case”是否比“ if..else”更好?
if (meals == null)
{
bfast.Hide();
lunch_rb.Hide();
dinner_rb.Hide();
}
else if (meals != null)
{
if (breakfast != null && lunch == null && dinner == null)
{
lunch_rb.Hide();
dinner_rb.Hide();
}
if (breakfast == null && lunch != null && dinner == null)
{
bfast.Hide();
dinner_rb.Hide();
}
if (breakfast == null && lunch == null && dinner != null)
{
bfast.Hide();
lunch_rb.Hide();
}
if (breakfast != null && lunch != null && dinner == null)
{
dinner_rb.Hide();
}
if (breakfast != null && lunch == null && dinner != null)
{
lunch_rb.Hide();
}
if (lunch != null && breakfast == null && dinner != null)
{
bfast.Hide();
}
I am developing an application for windows CE 5.0 (if this helps) 我正在开发Windows CE 5.0的应用程序(如果有帮助)
I think the better solution in this case is: 我认为在这种情况下更好的解决方案是:
if (breakfast == null)
bfast.Hide();
if (lunch == null)
lunch_rb.Hide();
if (dinner == null)
dinner_rb.Hide();
You can try something like this, As you have condition on multiple variables you will need to make expression for passing it to switch so using if as given below might make it simple. 您可以尝试这样的操作,因为您对多个变量有条件,您将需要创建表达式以将其传递给开关,因此使用if如下所示可能会使其变得简单。
if (breakfast == null)
bfast.Hide();
if (lunch == null)
lunch_rb.Hide();
if (dinner == null)
dinner_rb.Hide();
对于这种特殊情况,if-else更好,因为您具有复杂的条件,而我相信切换情况是无法做到的。
For this question, I think if...else
is good enough. 对于这个问题,我认为
if...else
是否足够好。 switch...case
cannot deal with such a complicated situation. switch...case
无法处理如此复杂的情况。 Feel free to use it. 随意使用它。
Switch case总是比if ... else if更好,因为它需要更少的输入,并且您的代码将更易于阅读和理解。当我忘记考试中的switch样式时,我自己只是使用“ else if”!
The performance level between if
and switch
statements is not much difference. if
和switch
语句之间的性能水平没有太大差异。 Anyway your code is a mess of conditions. 无论如何,您的代码都是一团糟。 Take into consideration the answer of Pigueiras.
考虑到Pigueiras的答案。 Something like
就像是
bfast.Hide();
lunch_rb.Hide();
dinner_rb.Hide();
if (meals != null) {
if (breakfast != null)
bfast.Show();
if (lunch =! null)
lunch_rb.Show();
if (dinner =! null)
dinner_rb.Show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.