Visual Studio null引用警告 - 为什么没有错误?

Tes*_*rex 5 c# compiler-construction nullreferenceexception visual-studio

我注意到Visual Studio特有的一些东西.首先,尝试在函数中的某处键入此(C#):

class Foo  
{  
    public void Bar()  
    {  
        string s;
        int i = s.Length;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,马上将迎来ss.Length是一个错误,说" Use of unassigned local variable 's'".另一方面,请尝试以下代码:

class Foo  
{  
    private string s;
    public void Bar()  
    {  
        int i = s.Length;
    }
}
Run Code Online (Sandbox Code Playgroud)

它将编译,并sprivate string s警告中强调中,并说" Field 'Foo.s' is never assigned to, and will always have its default value null".

现在,如果VS是那么聪明并且知道s将永远为null,为什么在第二个例子中得到它的长度不是错误?我最初的猜测是,"如果编译器根本无法完成其工作,它只会产生编译错误.由于代码在技术上运行只要你从不调用Bar(),它只是一个警告." 除非第一个例子使解释无效.只要你从不调用Bar(),你仍然可以毫无错误地运行代码.什么给出了什么?只是疏忽,还是我错过了什么?

Hen*_*man 8

第一个例子(错误)是编译器的明确赋值跟踪的一个例子,它只适用于局部变量.由于上下文有限,编译器对这种情况有一个密不透风的掌握.注意,s它不是null,它是未定义的.

在第二个示例中,s是一个字段(默认为null).没有编译器错误,但它将始终在运行时捕获.这种特殊情况可能会被困住,但编译器通常无法检测到这种错误.
例如,您可以添加一个方法Bar2()来分配字符串,s但稍后调用它Bar(),或者根本不调用它.这将消除警告,但不会消除运行时错误.

所以它是设计的.