有什么方法可以让 Visual Studio 忽略使用未分配对象的编译错误吗?
我的代码基本上看起来像这样(它实际上不是对象,而是一个自定义类):
object thing
try {
thing = new object();
......
} catch { stuff }
finally {
if (thing != null) { some clean up code }
但是 VS 不允许我这样做,因为它说我正在引用一个未分配的变量。我很清楚,运行此代码时它可能会被取消分配,这就是为什么存在空检查的原因。我不想在 try 块之外实例化该对象,因为它做了相当多的工作并且可能引发异常,而且我宁愿不要将整个对象包装在另一个 try/catch 中 阻止这样我就可以在那里实例化它。我还能做些什么吗?
I have code that basically looks like this (it isn't actually object, but rather a custom class):
object thing
try {
thing = new object();
......
} catch { stuff }
finally {
if (thing != null) { some clean up code }
But VS is not letting me do this because it says I am referencing an unassigned variable. I am well aware it could be unassigned when this code is run, which is why the null check is there. I don't want to instantiate the object outside of the try block because it does a fair bit and could throw an exception, and I would prefer against wrapping the whole thing in another try/catch block just so I can instantiate it up there. Is there something else I can do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
“未分配”与“空”不同。您的代码根本无效 - 您需要修复它。
这里非常简单 - 只需将变量初始化为
null
即可:现在它肯定会有一个值(空引用),因此您可以在
finally< 中读取它/代码> 块。
要点是,在编译器可以证明某个值(无论是否为 null)已明确被赋值之前,局部变量无法被读取。实际上,局部变量没有“默认值”。
(请注意,我通常会使用
IDisposable
来清理代码,以及using
语句。)"Unassigned" isn't the same as "null". Your code is simply invalid - you need to fix it.
It's very easy here - just initialize the variable to
null
to start with:Now it will definitely have a value (a null reference) so you're allowed to read from it in the
finally
block.The point is that local variables cannot be read before the point at which the compiler can prove that a value (whether null or not) has definitely been assigned. Effectively, local variables don't have "default values".
(Mind you, I'd normally use
IDisposable
for clean-up code, along with ausing
statement.)不,您无法禁用该编译器错误。但为什么不直接初始化变量呢?
与字段不同,局部变量不会自动初始化为
null
。它们未初始化,这是一种特殊状态,与null
不同。No, you can't disable that compiler error. But why don't you just initialize the variable?
Unlike fields, local variables don't get initialized to
null
automatically. They are uninitialized, which is a special state, distinct from beingnull
.只要这样做
,编译器就会得到安抚。
有关编译器抱怨此问题的背景,请参阅此 Eric Lippert 答案< /a>,由此而来:
Just do
and the compiler will be placated.
For background on why the compiler complains about this, see this Eric Lippert answer, whence:
怎么样:
how about:
最初设置为 null 有什么问题吗?
What is wrong with just setting to to null initially?
只需分配 null 即可:
Just assign null to begin with:
为什么不尝试 object thing = null;作为第一行?
Why not try object thing = null; as first line ?
将您的代码更改为此,它应该可以正常工作
change your code to this and it should work ok