如果你看下一个例子:
public void TestLocalValuesAssignment()
{
int valueVariable; // = default(int) suits fine
string refType; // null suits fine as well
try
{
valueVariable = 5;
refType = "test";
}
catch (Exception){}
Console.WriteLine("int value is {0}", valueVariable);
Console.WriteLine("String is {0}", refType);
}
您可以很容易地看到,变量 valueVariable
和 refType
在 Console.WriteLine()
中使用之前可以取消分配。编译器告诉我们错误:
Error 1 Use of unassigned local variable 'valueVariable'
Error 2 Use of unassigned local variable 'refType'
这是一个普遍的案例,并且有 loads of answers关于如何解决这个问题(评论了可能的修复)。
我不明白的是为什么会存在这样的行为? 这里的局部变量与类字段有何不同,如果未分配,最后一个变量将获得默认值(引用类型为空,值类型为对应的默认值)?也许有一个示例或极端案例可以解释为什么选择这种编译器行为?
最佳答案
基本上 - 这是 MS 的决定。
如果你想要更多,你可以阅读 here并检查 Eric Lippert’s Blog
The reason this is illegal in C# is because using an unassigned local has high likelihood of being a bug.
关于c# - 为什么 C# 局部变量应该直接赋值,即使它是默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210223/