c# - 为什么 C# 局部变量应该直接赋值,即使它是默认值?

标签 c# compiler-construction initialization default-value local-variables

如果你看下一个例子:

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);
}

您可以很容易地看到,变量 valueVariablerefTypeConsole.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/

相关文章:

java - 如何列出 Java 方法/函数中的所有局部变量?

c++ - 究竟为什么编译器直到运行时才能确定变量的真实类型?

c++ - 尽管有非默认构造函数参数,但在 const 引用成员上调用默认构造函数

c - 难倒 : for loop to build an array not working, 忽略初始条件?

java - 如何定义List<Map<String, Object>>的大小?

c# - unity3d开启关闭粒子系统

c# - 处理器架构与 SQLite Nuget 包和任何 CPU Web 项目不匹配

c# - SQL C# 尝试访问前 10 个值

c# - 如何在主布局文件中渲染部分 View 部分

iphone - 从 iPhone 静态库中提取对象 (*.o) 文件