假设我们有这两个字典:
var dict1 = new Dictionary<string, int>();
var dict2 = new Dictionary<char, string>();
dict1.Add("foo", 42);
dict2.Add('x', "bar");
// These variables will be used for getting values from the dicts
int number;
string text;
我们可以在 if
中毫无问题地使用 text
,在 中为它赋值(在本例中,通过
的条件:out
)如果
// Example 1
if(dict1.TryGetValue("foo", out number) &&
dict2.TryGetValue('x', out text))
{
Console.WriteLine(text); /* Prints: bar */
}
但是,如果我们将条件输出到一个 bool 变量,它不会编译:
// Example 2
var canPrint =
dict1.TryGetValue("foo", out number) &&
dict2.TryGetValue('x', out text);
if(canPrint)
{
Console.WriteLine(text); /*Use of unassigned local variable 'text'*/
}
为了让事情变得更奇怪,如果我们改变 canPrint
的条款的顺序,它会编译:
// Example 3
var canPrint =
dict2.TryGetValue('x', out text) &&
dict1.TryGetValue("foo", out number);
if(canPrint)
{
Console.WriteLine(text); /* Prints: bar */
}
我认为这是因为编译器确定变量赋值的方式(具体来说,当它们在 bool 表达式中定义时)。
无论如何,让我感到惊讶的是,第一个和第二个例子,看起来如此相似,却有如此不同的结果。
为什么会这样?
最佳答案
就是因为所谓的短路。在以下条件下,如果 dict1.TryGetValue("foo", out number)
为假,则 dict2.TryGetValue('x', out text)
将不会被计算所以 text
不会有值。
if (dict1.TryGetValue("foo", out number) && dict2.TryGetValue('x', out text))
如果条件为true
,则意味着两个谓词都被求值,这意味着text
被初始化,如果为false
,将不会执行试图访问 text
的 block 。
但是为什么 if(canPrint)
不起作用。实际上,关键是你可以独立地将 true
分配给 canPrint
而 false
而 text
还没有初始化。所以,没有保证,编译器会提示。
最后,要查看短路的效果,请交换两个条件的位置,然后它们(由于您使用它们的方式)都将起作用。
关于c# - 在 bool 连词中分配变量时出现意外的 "Use of unassigned local variable"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42356433/