我的情况需要检查
if(staffid!=23||staffid!=24||staffid!=25||staffid!=26||staffid!=27||staffid!=29||staffid!=31)
{
do the req thing ..
}现在我像这样检查条件。他们有没有更好的方法来写这个条件?
谢谢你
发布于 2009-10-05 12:46:11
将其他几个答案(mjv,意大利面,Mike Hofer,R. Bemrose)合并在一起,你就会得到以下代码。
至于代码:
if(!isStaffIDValid(staffid))
{
//do the req thing ..
}..。
然后在同一个类中,或者更好地在全局类中使用以下代码:
public static IList<int> notAllowedIDs = new int[] { 23, 24, 25, 26, 27, 29, 31 };
public static bool isStaffIDValid(int staffID)
{
return !notAllowedIDs.Contains(staffID);
}这提供了更易维护的代码,可以很容易地更新。
发布于 2009-10-05 12:44:54
嗯..。这不是等同于:
if (true) { do the req thing... }除非staffid可以同时是23、24、25、26、27、29和31。
假设有两种情况:
staffid = 23staffid != 23你的声明:
if(staffid!=23 ||
staffid!=24 ||
staffid!=25 ||
staffid!=26 ||
staffid!=27 ||
staffid!=29 ||
staffid!=31)
{
do the req thing ..
}Case 1通过第二个测试(staffid != 24),case 2通过第一个测试(staffid!=23)。因为case 1和case 2一起考虑了所有情况,所以staffid的所有值都应该通过您的测试。
发布于 2009-10-05 13:07:54
无法想象您的实际问题是什么,语句看起来是错误的。
如果在一个复杂的条件下有很多“not”,就把它转换成相反的。如果同时存在If和else部分,则将它们互换。如果没有其他选项,请在开头加上"not“。您的条件看起来是错误的,只是为了说明我的意思,这里是转换后的条件:
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 ..
}然后你就可以更容易地理解这种情况,更容易看到它不可能是你所需要的……
https://stackoverflow.com/questions/1519850
复制相似问题