固定用空赋值“未分配的局部变量的使用”。为什么? [英] Fixing the 'Use of unassigned local variable' with a null assignment. Why?

查看:85
本文介绍了固定用空赋值“未分配的局部变量的使用”。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过一段这样的代码,编译器会抱怨的 c.MyProperty

With a piece of code like this, the compiler complains on c.MyProperty:

MyClass c;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // "Use of unassigned local variable 'c'".



然而,如果您指定一个 C 在初始化:

MyClass c = null;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // no complains this time.



那么,为什么这项工作?如果 C 未分配和编译器假设使得它,就不会相同的异常被抛出时 c.MyProperty 对象引用未设置为一个对象

So, why does this work? If c wasn't assigned a null and the compiler hypothetically allowed it, wouldn't the same exception be thrown at c.MyProperty, Object reference not set to an instance of an object?

推荐答案

在您指定来你告诉编译器后退,因为你知道的比他更好,所以他不应该抱怨变量关于这一点。

When you assign null to the variable you're telling the compiler to back off because you know better than him so he should not complain about this.

这可能是由于这一事实,即分配被认为暗示了一个明确的操作开发者。

This is probably due to the fact that assigning null is considered to imply an explicit action by the developer.

这篇关于固定用空赋值“未分配的局部变量的使用”。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆