小编str*_*372的帖子

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

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

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

Dictionary<string, List<List<int>> VarsWithInfo;
Run Code Online (Sandbox Code Playgroud)

要替换:

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

接着就,随即:

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

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

c#

3
推荐指数
1
解决办法
106
查看次数

标签 统计

c# ×1