c# - null 和未初始化的区别?

标签 c# null initialization

当我在 C# 中编写以下代码时:

SqlCeCommand command;
try
{
    // The command used to affect the data
    command = new SqlCeCommand
                  { 
                     // init code removed for brevity
                  };

    // Do stuff 
    // Do more stuff
}
finally
{
    if (command != null)
        command.Dispose();
}

Resharper 提示我检查命令 != null。它说该命令可能未分配(因为它可能会在构建过程中以某种方式失败并仍然命中 try block )。

所以我将命令声明更改为 SqlCeCommand command = null;,大家都很高兴。

但我想知道有什么区别?

为什么它不默认为空? 含义:C# 不只是将局部变量默认为 null 有何好处?

最佳答案

局部变量没有默认值。语言的一部分。

关于c# - null 和未初始化的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5096639/

相关文章:

c# - .Net中创建的内存不足异常对象在哪里?

c# - 错误 : must declare a body because it is not marked abstract or extern

asp.net-mvc - ASP.NET MVC路由冲突-输入变量为空值

c# - 除非使用 "run as admin",否则在 Windows 10 上以编程方式创建计划任务失败

c# - 解决方案中的多个项目 : Interface naming convention

c++ - 使用 Windows 7 在 VS 中取消引用 null

Javascript 空检查似乎不起作用

c - 在 C 中重新初始化 const char 数组不会给出错误

javascript - 如何通过索引分配 Javascript 数组

c# - 静态常量自定义类