我有条件需要检查
if(staffid!=23||staffid!=24||staffid!=25||staffid!=26||staffid!=27||staffid!=29||staffid!=31)
{
do the req thing ..
}
Run Code Online (Sandbox Code Playgroud)
现在我检查这样的情况.是他们写这种情况的更好方法
谢谢
Chr*_*ris 25
将几个其他答案(mjv,pasta,Mike Hofer,R.Bemrose)合并在一起,您将得到以下代码.
至于代码:
if(!isStaffIDValid(staffid))
{
//do the req thing ..
}
Run Code Online (Sandbox Code Playgroud)
...
然后在同一个类中,或者更优选地,全局类使用以下代码:
public static IList<int> notAllowedIDs = new int[] { 23, 24, 25, 26, 27, 29, 31 };
public static bool isStaffIDValid(int staffID)
{
return !notAllowedIDs.Contains(staffID);
}
Run Code Online (Sandbox Code Playgroud)
这提供了可维护的代码,可以轻松更新.
Dom*_*ger 19
Errr ..不等同于:
if (true) { do the req thing... }
Run Code Online (Sandbox Code Playgroud)
除非staffid能同时为23和24以及25和26以及27和29以及31.
想象一下2例:
staffid = 23staffid != 23你的陈述:
if(staffid!=23 ||
staffid!=24 ||
staffid!=25 ||
staffid!=26 ||
staffid!=27 ||
staffid!=29 ||
staffid!=31)
{
do the req thing ..
}
Run Code Online (Sandbox Code Playgroud)
情况1通过第二个测试(staffid != 24),情况2通过第一个测试(staffid!=23).由于案例1和案例2共同考虑了所有案例,因此所有值staffid都应通过您的测试.
无法想象你的实际问题是什么,声明看起来不对.
如果在复杂条件下有很多"不",只需将其转换为相反的情况.如果同时存在if和else部分,则交换它们.如果没有别的,就把"不"放到开头.你的情况看起来不对,只是为了表明我的意思,这是转换后的:
if (staffid == 23
&& staffid == 24
&& staffid == 25
&& staffid == 26
&& staffid == 27
&& staffid == 29
&& staffid == 31)
{
//if there was an else block before, it will be here now.
}
else
{
//do the req thing ..
}
Run Code Online (Sandbox Code Playgroud)
然后你可以更容易地了解情况,更容易看出它不是你需要的......
| 归档时间: |
|
| 查看次数: |
655 次 |
| 最近记录: |