首页 > 解决方案 > 为什么这个三元语句在简写时会返回误报?

问题描述

我一直在摸索这个问题,因为除了格式之外,这些语句似乎几乎相同 - 但是速记语句的评估方式似乎不同,并且在不应该返回 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,但是缩写版本不会发生这种情况。

标签: c#booleanternary-operatorboolean-expressionshort-circuiting

解决方案


您比较的格式是错误的。如果要正确解释,您实际上需要括号来强制内联。

你应该有以下内容

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;
}

推荐阅读