什么是使用“!”的好方法"在比较声明中? [英] What is a good alternative to using "! " in a comparison statement?
问题描述
最近我正在审查我几个月前写的一些代码并浪费时间,因为我错过了一个!在下面的比较之前
Recently I was reviewing a some code I'd written a few months back and wasted time because I missed a "!" preceding a comparison like below
if(!string.IsNullOrWhiteSpace(parm)){// Do some stuff...
}
我不知道它是否被认为是一种不好的做法,但它很容易错过,所以什么是好的选择?
我试过的:
I don't know if it's considered a bad practice but it's defiantly easy to miss, so what is a good alternative?
What I have tried:
if(!string.IsNullOrWhiteSpace(parm)){// Do some stuff...
}
if(string.IsNullOrWhiteSpace(parm) != true){
// Do some stuff...
// Best solution so far, but
// seems like the coding equivalent of a double negative.
// ie. "!= true", should just be "false".
}
if(!string.IsNullOrWhiteSpace(parm)){// Do nothing but waist space and bytes}
else{// Do some stuff..
}
为了我自己的娱乐,我想指出即使代码项目文字处理器也会错过解释它。 />
For my own amusement I'd like to point out that even the Code Project word processor miss interpreters it.
!string.IsNullOrWhiteSpace(parm)
应该看起来像这样没有空间
should look like this with out the space
! string.IsNullOrWhiteSpace(parm)
推荐答案
就我个人而言,我会使用变体@RichardDeeming在评论中写道,但只是为了玩一下,你也可以使用扩展方法。请考虑以下事项:
Personally I'd use the variation @RichardDeeming wrote in the comment but just to play around a bit, you could also use an extension method. Consider the following:
public static class X {
public static bool IsNotNullOrWhiteSpaceOrSomeOtherDescriptiveName(this string value) {
return !string.IsNullOrWhiteSpace(value);
}
}
现在你可以在你的代码中使用它
Now you could use this in your code
string a = "";
string b = "a";
if (a.IsNotNullOrWhiteSpaceOrSomeOtherDescriptiveName()) {
System.Diagnostics.Trace.WriteLine("a contains something meaningful");
}
if (b.IsNotNullOrWhiteSpaceOrSomeOtherDescriptiveName()) {
System.Diagnostics.Trace.WriteLine("b contains something meaningful");
}
但是正如所说的只是使用不同的名称进行比较并没有真正增加任何价值,只会引入更多的复杂性所以我会用它仅当您计划在比较中添加一些额外的检查或操作时才接近。
But as said just using a different name for a comparison does not really add any value, only introduces a bit more complexity so I'd use this approach only if you're planning to add some additional checks or operations to the comparison.
这篇关于什么是使用“!”的好方法"在比较声明中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!