c# - 在 bool 连词中分配变量时出现意外的 "Use of unassigned local variable"错误

标签 c#

假设我们有这两个字典:

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 分配给 canPrintfalsetext 还没有初始化。所以,没有保证,编译器会提示。

最后,要查看短路的效果,请交换两个条件的位置,然后它们(由于您使用它们的方式)都将起作用。

关于c# - 在 bool 连词中分配变量时出现意外的 "Use of unassigned local variable"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42356433/

相关文章:

c# - IMongoCollection.AsQueryable() 是否延迟?

c# - 如何创建元素自动实例化数组,例如用户自定义类型的int数组?

c# - 使用子集合更新 NHibernate 对象

c# - 在 C# 应用程序中获取雅虎联系人列表

c# - wcf 休息服务消息记录

c# - 致命异常,如何捕捉?系统.Net.InternalException : System error

c# - 如何从标准中获取 ip 地址信息?

c# - 安全与不安全代码

c# - 从代码创建 Dot Net Nuke 用户

c# - "PDB format is not supported"带有 .NET 可移植调试信息