范围外的内联变量声明

Inline variable declaration outside of scope

假设我有两个具有相同键但具有不同值的字典。

var metrics1 = new Dictionary<string, double>()
{
    { "Albert", 1.5513 },
    { "Becca", 3.3184 },
    { "Colton", -4.4001 },
    { "Danielle", 6.7 }
};
var metrics2 = new Dictionary<string, double>()
{
    { "Albert", 0.84156 },
    { "Becca", -6.7525 },
    { "Colton", 1.1102 },
    { "Danielle", 0.507944 }
};

如果我随后使用三元运算符 ?: 随机选择一个字典来获取值,Visual Studio 说我可以内联声明一个变量。

var rng = new Random();
var name = "Albert"; // Any name that's present in both dictionaries above

/* Unmodified code */
double metric;
var validName = rng.NextDouble() > 0.5
                    ? metrics1.TryGetValue(name, out metric)
                    : metrics2.TryGetValue(name, out metric);

/* After suggestion was applied */
// double metric;
var validName = rng.NextDouble() > 0.5
                    ? metrics1.TryGetValue(name, out double metric) // 'metric' is declared here?
                    : metrics2.TryGetValue(name, out metric);

为什么修改版的metric变量可以被三元?:运算符的两边填充?不应该完全包含在第一个分支的范围内吗?

让我先回答您的评论,// 'metric' is declared here?。是的,metric 在那里被声明(好吧……从技术上讲不是……见下文)。要测试这一点,请尝试在三元语句的第二部分声明它;如果你这样做,你会得到,

error CS0841: Cannot use local variable 'metric' before it is declared

在包含第一条手臂的线上。至于,

Why is it that the metric variable in the modified version can be populated by both sides of the ternary ?: operator?

因为编译器将该代码编译成 IL,看起来类似于为先前代码生成的 IL,这意味着在这两种情况下声明都在 两者臂的三元赋值.

因此,

Should it not be contained entirely in the scope of the first branch?

答案是否定的,因为在这两种情况下,声明都在三元赋值上方的方法范围内,而三元赋值也在该范围内。

从本质上讲,第二个实现只是第一个的 syntactic sugar