为什么三元运算符不替换if-else

时间:2019-10-07 09:08:29

标签: c#

我遇到了一个小问题和知识鸿沟

我发现使用If-Else样式有时太样板了,想用elvis-operator代替它,例如:

Dictionary<string, List<List<int>> VarsWithInfo;

要替换:

if (VarsWithInfo.ContainsKey(ruleVar))
    {
        VarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks };
    }
else
    {
        VarsWithInfo[ruleVar].Add(NestingBlocks);
    }

附带:

VarsWithInfo.ContainsKey(ruleVar) ?
    VarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks } :
    VarsWithInfo[ruleVar].Add(NestingBlocks);

我知道在这种情况下与ternar运算符的行太长,但我想知道主要原因。 谢谢。

1 个答案:

答案 0 :(得分:11)

  

条件运算符?:(通常称为三元条件运算符)对布尔表达式求值,并根据布尔表达式的取值为true或false来返回对两个表达式之一求值的结果

From MSDN

三元运算符始终返回一个值。在表达式x = a ? b : c中,如果atrue,则它将b的值分配给x,否则它将分配{{1 }}到c

因此,xb都必须是产生值的表达式,并且这些值都必须是同一类型。

cVarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks }都不是表达式,它们都不返回值。因此,它们不能用于三元组。


我假设您的代码应该为:

VarsWithInfo[ruleVar].Add(NestingBlocks)

常见的写法是:

if (!VarsWithInfo.ContainsKey(ruleVar))
{
    VarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks };
}
else
{
    VarsWithInfo[ruleVar].Add(NestingBlocks);
}

这避免了重复的字典查找(即调用if (!VarsWithInfo.TryGetValue(ruleVar, out var list)) { list = new List<List<int>>(); VarsWithInfo[ruleVar] = list; } list.Add(NestingBlocks); 然后从VarsWithInfo.ContainsKey(ruleVar)读取)。

相关问题