加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么这个C#代码会抛出错误:使用未分配的局部变量’n’

发布时间:2020-12-15 20:01:07 所属栏目:百科 来源:网络整理
导读:在MSDN上,此代码发布于 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch我无法理解为什么它会抛出错误: Use of unassigned local variable ‘n’. static void Main() { int n; try { // Do not initialize this va
在MSDN上,此代码发布于 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch我无法理解为什么它会抛出错误:

Use of unassigned local variable ‘n’.

static void Main()   
{  
    int n;  

    try   
    {  
        // Do not initialize this variable here.  
        n = 123;  
    }  
    catch  
    {  
    }  

    // Error: Use of unassigned local variable 'n'.  
    Console.Write(n);  
}

解决方法

Compiler Error CS0165

The C# compiler does not allow the use of uninitialized variables. If
the compiler detects the use of a variable that might not have been
initialized,it generates compiler error CS0165. For more information,
see 07001. Note that this error is generated when the compiler
encounters a construct that might result in the use of an unassigned
variable,even if your particular code does not. This avoids the
necessity of overly-complex rules for definite assignment.

更多的是,想象一下这种情况

int n;  

try   
{  
    throw new Exception();
    n = 123;  // this code is never reached
}  
catch  
{  
}  

// oh noez!!! bam!
// The compiler is trying to be nice to you 
if(n == 234);

简而言之,计算机说没有

注意:当您在visual studio中遇到编译器错误时,您可以单击错误代码,有时(如果您很幸运)可以为您提供有关错误含义的更简明信息

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读