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

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...