我如何写一个“如果条件”不同 [英] How do I write a "If Condition" differently
问题描述
我的代码有一个IF条件,我在检查特定值是否介于一组整数之间(如26,34,58,112等) 。我已经通过OR运算符(||)编写它们但是它变成了一个很长的语句来查看。
代码的例子可以是这样的..
如果(StatusOfCondition =26)|| (StatusOfCondition =28)|| (StatusOfCondition =34)等等
还有其他方法我可以写一个循环并缩短它吗?
感谢任何帮助。
有很多方法可以做到这一点:特别是如果你设置一个数组或允许值列表 - 可以是静态只读列表。
第一种是使用开关代替:
string StatusOfCondition = 26 跨度>;
switch (StatusOfCondition)
{
case 26:
case 28:
case 34:
// 做点什么
break ;
默认:
// 为不匹配的值做一些事情
break ;
}该框架可以很好地优化交换机。
阵列版本可能更好:
私有 静态 readonly string [] allowedValues = new string [] {< span class =code-string> 26, 28, 34};
...
string StatusOfCondition = 26\" 跨度>;
if (allowedValues.Contains(StatusOfCondition))
{
...
}
// 创建整数列表使用以下所有选项
var list = new List< int> { 26 , 34 , 58 ,< span class =code-digit> 112 };
var StatusOfCondition = 58 ; // 用于测试..
// 您可以简单地使用包含下面的方法
if (list.Contains( StatusOfCondition))
{
// 做点什么
}
Hi,
My code has a IF condition where I am checking if a particular value falls between a set of integers (like 26,34,58,112 etc). I have written them through a OR operator (||) however it becomes a long statement to view.
The example of the code can be this way..
If (StatusOfCondition = "26") || (StatusOfCondition = "28") || (StatusOfCondition = "34") etc etc
Is there any other way through which I can write a loop and make it shorter?
Any help is appreciated.
There are quite a lot of ways you can do that: particularly if you set up an array or list of "allowed values" - which can be a static readonly list.
The first is to use a switch instead:
string StatusOfCondition = "26"; switch (StatusOfCondition) { case "26": case "28": case "34": // Do something break; default: // Do something for non matching values break; }The framework can optimise switches pretty well.
The array version may be better though:
private static readonly string[] allowedValues = new string[] { "26", "28", "34" }; ... string StatusOfCondition = "26"; if (allowedValues.Contains(StatusOfCondition)) { ... }
// create list of integers with all options like below var list = new List<int> {26,34,58,112}; var StatusOfCondition = 58; // for testing.. //you can simple use Contains method like below if(list.Contains(StatusOfCondition)) { // do something }
这篇关于我如何写一个“如果条件”不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!