And*_*ech 32 c# exception variable-assignment
使用这样的一段代码,编译器抱怨c.MyProperty:
MyClass c;
try { throw new Exception(); }
catch (Exception) { }
c.MyProperty = 2; // "Use of unassigned local variable 'c'".
Run Code Online (Sandbox Code Playgroud)
然而,如果你指定一个不抱怨null到c在初始化:
MyClass c = null;
try { throw new Exception(); }
catch (Exception) { }
c.MyProperty = 2; // no complains this time.
Run Code Online (Sandbox Code Playgroud)
那么,为什么这有效呢?如果c未分配a null并且编译器假设允许它,则不会抛出相同的异常c.MyProperty,Object引用未设置为对象的实例?
Joã*_*elo 66
当你分配null给变量时,你告诉编译器退出,因为你比他更了解所以他不应该抱怨这个.
这可能是由于分配null被认为意味着开发人员采取明确的行动.