【发布时间】:2019-04-28 12:45:59
【问题描述】:
我一直在摸不着头脑,因为除了格式之外这些语句看起来几乎相同 - 但是速记语句似乎评估不同,并且在不应该返回 true 时会产生误报。
在下面的例子中,想象一下programRecord.Award = 'Emmy' 和targetAward = 'Oscar'
给出误报的错误代码:
private bool MatchMe(string programId, string targetAward, string targetLevel, Program programRecord)
{
var isMatched = programRecord.Status == "Active"
&& string.IsNullOrEmpty(programId) ? true : programRecord.Pid == programId
&& string.IsNullOrEmpty(targetAward) ? true : programRecord.Award == targetAward
&& string.IsNullOrEmpty(targetLevel) ? true : programRecord.Level == targetLevel;
return isMatched;
}
好代码:
private bool MatchMe(string programId, string targetAward, string targetLevel, Program programRecord)
{
var isMatched = programRecord.Status == "Active";
var isMatched2 = string.IsNullOrEmpty(programId) ? true : programRecord.Pid == programId;
var isMatched3 = string.IsNullOrEmpty(targetAward) ? true : programRecord.Award == targetAward;
var isMatched4 = string.IsNullOrEmpty(targetLevel) ? true : programRecord.Level == targetLevel;
var doIMatch = isMatched && isMatched2 && isMatched3 && isMatched4;
return doIMatch;
}
导致这种情况的速记版本中发生了什么?我认为一个 false 值会强制整个语句返回 false,但是缩写版本不会发生这种情况。
【问题讨论】:
-
旁注,您可以使用
or逻辑,而不是使用三元运算符。(string.IsNullOrEmpty(programId) || programRecord.Pid == programId)。看到这是操作顺序的问题,做这个方法会很快突出问题。
标签: c# boolean ternary-operator boolean-expression short-circuiting