为什么此C#代码会引发错误:使用未分配的局部变量'n' [英] Why does this C# code throw an error: Use of unassigned local variable 'n'

查看:63
本文介绍了为什么此C#代码会引发错误:使用未分配的局部变量'n'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MSDN上,此代码发布在 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/try-catch 我无法理解为什么会引发错误:

使用未分配的局部变量'n'.

  static void Main(){int n;尝试{//不要在此初始化此变量.n = 123;}抓住{}//错误:使用未分配的局部变量'n'.Console.Write(n);} 

解决方案

编译器错误CS0165

C#编译器不允许使用未初始化的变量.如果编译器检测到可能未使用过的变量的使用初始化后,它会生成编译器错误CS0165.想要查询更多的信息,请参见字段.请注意,此错误是在编译器时生成的遇到构造可能会导致使用未分配的构造变量,即使您的特定代码没有.这样可以避免确定分配的规则过于复杂的必要性.

更多,请想象这种情况

  int n;尝试{抛出新的Exception();n = 123;//永远不会到达此代码}抓住{}//哦,天哪!!//编译器正尝试对您友好if(n == 234); 

简而言之,计算机说不

注意:在Visual Studio中遇到编译器错误时,您可以单击错误代码,有时(如果幸运的话)会为您提供有关错误含义的更简洁的信息

On MSDN, this code is posted at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch I am unable to understand why it throws the error:

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 Fields. 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.

More-so, imagine this situation

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);

In short, computer says no

Note : when you get a compiler error in visual studio, you can click on the error code and it sometimes (if you are lucky) gives you more concise information about what the error means

这篇关于为什么此C#代码会引发错误:使用未分配的局部变量'n'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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