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)
现在,马上将迎来s
的s.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)
它将编译,并s
在private string s
警告中强调中,并说" Field 'Foo.s' is never assigned to, and will always have its default value null
".
现在,如果VS是那么聪明并且知道s将永远为null,为什么在第二个例子中得到它的长度不是错误?我最初的猜测是,"如果编译器根本无法完成其工作,它只会产生编译错误.由于代码在技术上运行只要你从不调用Bar(),它只是一个警告." 除非第一个例子使解释无效.只要你从不调用Bar(),你仍然可以毫无错误地运行代码.什么给出了什么?只是疏忽,还是我错过了什么?
归档时间: |
|
查看次数: |
1040 次 |
最近记录: |