在finally块上使用未分配的局部变量 [英] Use of unassigned local variable on finally block

查看:110
本文介绍了在finally块上使用未分配的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中什么时候可以取消分配i?

When could i in this example be unassigned?

int i;
try
{
    i = 2;
}
catch
{
    i = 3;
}
finally
{
    string a = i.ToString();
}

推荐答案

例如,您可以在i = 2运行之前得到ThreadAbortException.无论如何,C#编译器不是特别聪明,因此容易被上面的例子弄糊涂了.它不必识别所有情况,并且即使不确定,也不确定会分配给它.

You could get a ThreadAbortException before i=2 runs, for example. Anyway, the C# compiler is not exceptionally smart, so it's easy to fool with contrived examples like the above one. It doesn't have to recognize every situation, and if it's not sure it is assigned, even if you are sure, it will complain.

我在第一个假设时有点敏捷.因此,为了完善它,这就是我的想法.确保代码按顺序运行,否则,如果发生异常,它将跳转到处理程序.因此,如果在此之前发生异常,则i = 2可能不会运行.我仍然声称ThreadAbortException是发生这种情况的少数原因之一,即使您没有可以产生异常的代码也是如此.通常,如果您有许多不同的异常处理程序,则编译器无法事先知道将运行哪个异常处理程序.因此,它不会对此做出任何假设.它可以知道,如果1)只有1个catch块,而2)它是无类型的,那么只有这样,才能保证一个catch块可以运行.或者,如果有多个catch处理程序,并且您在每个处理程序中都分配了变量,它也可以工作,但是我想编译器也不在乎.看起来多么简单,这都是一种特殊情况,C#编译器团队倾向于忽略这些特殊情况.

I was a bit quick on my first assumption. So to refine it, here's what I think. Code is guaranteed to run in order, or if an exception happens, it will jump to the handlers. So i=2 may not run if an exception happens before that. I still claim that a ThreadAbortException is one of the few reasons why this can happen, even you have no code which could produce exceptions. Generally, if you have any number of different exception handlers, the compiler cannot know in advance which one will run. So it doesn't try to make any assumptions about that. It could know that if 1) there is only 1 catch block and 2) it is typeless, then, and only then, that one catch block is guaranteed to run. Or, if there were multiple catch handlers, and you assigned your variable in every one of them, it could also work, but I guess the compiler doesn't care about that either. However simple it may seem, it is a special case, and the C# compiler team has a tendency to ignore those special cases.

这篇关于在finally块上使用未分配的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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