<分区>
给定这段代码:
private void TryIt(Dictionary<int, int> myDict)
{
if (myDict?.TryGetValue(1, out int myValue) ?? false)
{
Console.Out.WriteLine(myValue); // <-- Error CS0165
}
}
C# 编译器发出:
error CS0165: Use of unassigned local variable 'myValue'
但显然不能引用myValue
当调用 TryGetValue()
被 ?.
跳过运算符(operator)。这是因为生成的 null
转换为 false
通过 ?? false
.
换句话说,如果 myDict
是null
, ?.
接线员将跳过对 TryGetValue()
的调用, 离开 myValue
未分配。我明白了。
但是 ??
然后,运算符将始终评估该空传播到 false
,在这种情况下阻止进入 if block 。
这在编译时很明显,那么为什么会出错呢?
我怀疑这可能与所有这些语法糖最终如何分解为实际的 .NET p 代码有关,但出错似乎仍然是错误的...
不使用 .?
时运算符(operator),我没有收到任何错误,这是预期的:
if (myDict.TryGetValue(1, out int myValue))
{
Console.Out.WriteLine(myValue); // <-- NO ERROR
}
就在我用.?
的时候与 ?? false
.