gpt4 book ai didi

c# - 为什么此 C# 代码会引发错误 : Use of unassigned local variable 'n'

转载 作者:行者123 更新时间:2023-11-30 13:09:01 27 4
gpt4 key购买 nike

在 MSDN 上,此代码发布在 https://learn.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 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.

更是如此,想象一下这种情况

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

关于c# - 为什么此 C# 代码会引发错误 : Use of unassigned local variable 'n' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51146590/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com