微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在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中遇到编译器错误时,您可以单击错误代码,有时(如果您很幸运)可以为您提供有关错误含义的更简明信息

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐