使用未分配的局部变量.但总是落入任务中 [英] Use of unassigned local variable. But always falls into assignment

查看:105
本文介绍了使用未分配的局部变量.但总是落入任务中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这段代码,我不明白为什么如果在finally块中分配变量不理解,为什么总是会分配它.我想我错过了不会分配货币的有效选择.如果您知道的话,将很高兴理解其中的原因.非常感谢!

having this code, I don't understand why if assigning a variable in a finally block doesn't understand it will ALWAYS be assigned. I think I missing a valid option where currency won't be assigned. If you know, will be great to understand why. much appreciate it!

谢谢!

CurrencyVO currency;

try
{
     if (idConnection.HasValue && idConnection != 0)
     {
         currencyConnection = client.GetConnection(idConnection.Value);
         model.Connection = currencyConnection;
     }
     else 
     {
         int providerUserKey = (int)Models.UserModel.GetUser().ProviderUserKey;
         currencyConnection = client.GetConnection(providerUserKey);
     }                        
     currency = model.Currencies.SingleOrDefault(c => c.IdCountry == currencyConnection.idcountry) ?? new CurrencyVO();    
} 
catch
{
      currency = new CurrencyVO();                    
} 
finally
{
      model.PublishedContainer.Currency = currency;
}

错误发生在finally块上.如果我把它从finally块中取出:

the error happens on the finally block. If i take it out of the finally block like this :

                } catch {
                    currency = new CurrencyVO();
                }
                model.PublishedContainer.Currency = currency;

它工作正常.

推荐答案

C#编译器执行的确定分配跟踪不一定执行完整的分析(在一般情况下是不可能的)-有规则限制了编译器将执行的分析的复杂程度. http://msdn.microsoft .com/en-us/library/aa691181.aspx :

The definite assignment tracking that the C# compiler performs doesn't necessarily perform a complete analysis (that wouldn't be possible in the general case) - there are rules that restrict how complex of an analysis the compiler will perform. The rule covering the finally block here is documented at http://msdn.microsoft.com/en-us/library/aa691181.aspx:

对于以下形式的try语句 stmt :

try 尝试阻止 finally 最终阻止

  • try-block 开头的v的明确分配状态与在 try-block 开头的v的明确分配状态相同. stmt 的开头.
  • finally-block 开头的v的明确分配状态与v处的明确分配状态相同 stmt 的开头.
  • ...
  • The definite assignment state of v at the beginning of try-block is the same as the definite assignment state of v at the beginning of stmt.
  • The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt.
  • ...

因此,在您的特定示例中,由于未明确在try块的开头分配currency,因此认为未明确将其分配在finally块的开头.

So for your particular example, since currency is not definitely assigned at the beginning of the try block, it is considered to be not definitely assigned at the beginning of the finally block.

这篇关于使用未分配的局部变量.但总是落入任务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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