我曾多次看到类似下面的内容……我讨厌它。这基本上是在“欺骗”语言吗?或者.. 您是否认为这是“好的”,因为 IsNullOrEmpty 总是首先被评估?
(我们可以争论一个字符串从函数中出来时是否应该为 NULL,但这不是真正的问题。)
string someString;
someString = MagicFunction();
if (!string.IsNullOrEmpty(someString) && someString.Length > 3)
{
// normal string, do whatever
}
else
{
// On a NULL string, it drops to here, because first evaluation of IsNullOrEmpty fails
// However, the Length function, if used by itself, would throw an exception.
}
编辑: 再次感谢大家提醒我这个语言基础。虽然我知道它“为什么”起作用,但我不敢相信我不知道/不记得这个概念的名称。
(以防万一有人想要任何背景。我在解决由 NULL 字符串和 .Length > x 异常生成的异常时遇到了这个问题......在代码的不同位置。所以当我看到上面的代码时,除了其他一切,我的挫败感从那里接管了。)
最佳答案
您正在利用一种称为短路的语言功能。这不是在欺骗语言,而是实际上使用了一个功能,它完全按照设计的方式使用。
关于c# - 我不喜欢这样……这是在欺骗语言吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/836945/