简体   繁体   English

为什么此 C# 代码会引发错误:使用未分配的局部变量 'n'

[英]Why does this C# code throw an error: Use of unassigned local variable 'n'

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:在 MSDN 上,此代码发布在https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch我无法理解为什么会引发错误:

Use of unassigned local variable 'n'.使用未分配的局部变量“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 编译器错误 CS0165

The C# compiler does not allow the use of uninitialized variables. C# 编译器不允许使用未初始化的变量。 If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165.如果编译器检测到使用了可能尚未初始化的变量,则会生成编译器错误 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注意:当您在 Visual Studio 中遇到编译器错误时,您可以单击错误代码,有时(如果幸运的话)它会为您提供有关错误含义的更简洁的信息

I believe, what you're confused about, is that even though the variable n appears to be initialized, why the compiler complains it isn't?我相信,您感到困惑的是,即使变量n似乎已初始化,为什么编译器会抱怨它没有初始化?

And there's a good reason for that;这是有充分理由的; even though n is initialized at one point, it isn't initialized in all possible paths .即使n在某一时刻初始化,它也不会在所有可能的路径中初始化。 In other words, you have to account for each scenario in your code and ensure that in all of them, the initialization occurs.换句话说,您必须考虑代码中的每个场景,并确保在所有场景中都进行了初始化。

But in this case, it doesn't satisfy that condition.但在这种情况下,它不满足该条件。 In your try block, if there was an exception before the program gets to execute the n = 123;在您的try块中,如果在程序执行之前出现异常,则n = 123; line, the program will go to the catch and then following that, will go to your Console.Write(n) line at which point you're trying to print a variable that isn't initialized.行,程序将转到catch ,然后转到您的Console.Write(n)行,此时您正在尝试打印未初始化的变量。

So, the best way to prevent such a scenario is to initialize the variable before the try block.因此,防止这种情况的最佳方法是在try块之前初始化变量。 In general it is advised that you always initialize a variable as soon as it is declared.通常,建议您始终在声明变量后立即对其进行初始化。


EDIT编辑

From a beginner's point of view, you might argue that there's only one line of code inside the try block, and therefore there's no way the program will not execute the initialization.从初学者的角度来看,您可能会争辩说try块中只有一行代码,因此程序不可能不执行初始化。 But you must look at it from the compiler's perspective;但是你必须从编译器的角度来看待它; it doesn't understand the intention of your program, it simply verifies (that's what a compiler does) if a program is written according to a predefined set of rules.它不理解你的程序的意图,它只是验证(这就是编译器所做的)程序是否是根据一组预定义的规则编写的。 And in this case, it isn't.在这种情况下,它不是。

If you look at the article, you'll see the answer:如果你看这篇文章,你会看到答案:

// Error: Use of unassigned local variable 'n'. // 错误:使用未赋值的局部变量“n”。

When you write int n;当你写int n; you do not initialize variable and try to use it in Console.Write(n);您不初始化变量并尝试在Console.Write(n);使用它Console.Write(n); , so you will get compilation error: https://ideone.com/q3LXwl ,所以你会得到编译错误: https : //ideone.com/q3LXwl

This error is because you are using n in Console.Write() function.此错误是因为您在Console.Write()函数中使用了n And suppose if Try block generates an exception then n would not be initialized.并假设如果Try块生成异常,则n不会被初始化。 Therefore this error occurs.因此发生此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM