简体   繁体   English

为什么我不能在try块中分配对象变量?

[英]why can't I assign object variables within the try block?

Why can't I assign object variables within the try block? 为什么我不能在try块中分配对象变量?

If I attempt to do this and clean up the variable in the finally block I get a compiler error: "use of unassigned local variable" . 如果我尝试执行此操作并清理finally块中的变量,则会出现编译器错误: “使用未分配的局部变量” This makes no sense because the variable is declared before the try block, and in the finally block I am first checking whether the variable is null . 这没有任何意义,因为变量是在try块之前声明的,而在finally块中我首先检查变量是否为null

Why can't the following code compile? 为什么以下代码无法编译? I am checking whether dbc is null so there's no chance of it trying to do something with an unassigned variable. 我正在检查dbc是否为null因此没有机会尝试使用未分配的变量。

eg: 例如:

DbConnection dbc;
try {
    dbc = <some method call returning an open DbConnection>
    // do stuff
} catch (Exception e) { // do stuff }
finally { 
    if (dbc != null) {
        dbc.Close();
    }
}

Change your declaration to DbConnection dbc = null; 将您的声明更改为DbConnection dbc = null; so the compiler can know for certain that the variable is assigned. 所以编译器可以确定已经分配了变量。 (Merely declaring dbc is not the same as assigning it a value of null, you must be explicit with a local.) (仅仅声明 dbc与为其赋值null不同,您必须使用本地显式。)

The reason your existing code fails is that it is entirely possible for an exception to occur before dbc is set. 现有代码失败的原因是在设置dbc之前完全可能发生异常。 As such, the compiler cannot assume that dbc is assigned by the time the finally block executes. 因此,编译器不能假定在finally块执行时分配dbc。

For more info, see section 5.3 of the language specification on definite assignment. 有关详细信息,请参阅有关明确赋值的语言规范的第5.3节。

http://msdn.microsoft.com/en-us/library/aa691172(VS.71).aspx http://msdn.microsoft.com/en-us/library/aa691172(VS.71).aspx

Change this 改变这个

DbConnection dbc;

to this 对此

DbConnection dbc = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM