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