或条件如果条件

hap*_*ile 0 c#

我有条件需要检查

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)合并在一起,您将得到以下代码.

  1. 使用函数来测试人员ID是否有效,这样您只需要更改一个地方.
  2. int数组没有Contains方法,因此您需要将其转换为IList(除非使用System.Linq命名空间中3.0中提供的扩展方法).

至于代码:

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)

这提供了可维护的代码,可以轻松更新.

  • 可以使用`HashSet <int>`:`private static HashSet <int> excluded = new HashSet <int>(new [] {...});`然后`return!excluded.Contains(id)`. (4认同)

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例:

  1. staffid = 23
  2. staffid != 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都应通过您的测试.

  • 我不认为这是他的意图.;) (2认同)
  • @Chris - 我也不是,但我认为可能更值得指出他的代码被打破,而不是猜测他的意图. (2认同)

Ste*_*ger 7

无法想象你的实际问题是什么,声明看起来不对.

如果在复杂条件下有很多"不",只需将其转换为相反的情况.如果同时存在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)

然后你可以更容易地了解情况,更容易看出它不是你需要的......

  • +1,De Morgans获胜!此外,它更容易显示逻辑中的错误. (2认同)