c#帮助检查两边的OR

本文关键字:OR 帮助 检查 | 更新日期: 2023-09-27 17:50:32

这应该是一个简单的问题,但作为一个新手,我不知道答案。

在下面的代码中,如果ignorePath为true,即使tempPath不为空且tempPath长度不为0,我也不想输入if语句。我以为一个单独的|就能做到这一点,但它似乎没有。

if (((tempPath != null) && (tempPath.Length != 0)) | ignorePath == false)
{
}

谢谢

c#帮助检查两边的OR

我认为下面的代码会更清晰:

if ((!ignorePath) && (tempPath != null) && (tempPath.Length != 0))
{
    // do something here
}

首先验证ignorePath为假(因为您不希望代码在其为真时执行),然后检查tempPath不是null并且其长度非零。

这里的优点是您已经将ignorePath变量的检查移到了第一个。由于它显然是对您最重要的事情(它覆盖了其他两个条件),因此它应该放在首位,以确保清晰性和可读性(以及性能,我想,但这在这里几乎不重要)。

请记住,没有理由根据字面值truefalse检查布尔类型。if语句已经计算了( )内部语句的值是true还是false。明确指定它只是多余的。

我看到上面代码的唯一问题是!ignorePath有点难以阅读。这会造成双重否定,因为你"没有忽略"某件事。这到底是什么意思?这就是为什么大多数编码标准(包括微软推荐的。net标准)鼓励您使用语法来命名布尔变量。我把这个变量叫做checkPath之类的东西。

if (!ignorePath || ((tempPath != null) &&(tempPath。

那么,如果我理解清楚的话,当ignorePathtrue时,您要忽略if语句吗?所以不需要OR,这是第三个AND条件。

if (ignorePath == false && tempPath != null && tempPath.Length != 0)
{
}

看起来tempPath是一个字符串,所以您可以这样编写代码:

if(!string.IsNullOrEmpty(tempPath) && !ignorePath)
{
}

您需要 &&运算符,因为您希望两个条件都为真以进入if。

像这样修改:

if (!ignorePath)
   if ((tempPath != null) && (tempPath.Length != 0)))
{
}

if (!ignorePath && ((tempPath != null) && (tempPath.Length != 0)))
{
}