“使用未分配的局部变量”错误,即使我分配变量吗? [英] "Use of unassigned local variable" error even though I assign the variable?
问题描述
在下面的例子中,编译器生成一个错误使用未分配的局部变量 r
,即使我在循环中分配变量在使用它之前。为什么编译器会生成此错误?
In the example below, the compiler generates an error "Use of unassigned local variable r
", even though I assign the variable in loop before using it. Why does the compiler generate this error?
static void Main(string[] args)
{
float r;
for (int i = 0; i < 100; i++)
r = i; // assigned here
Console.WriteLine(r); // error: use of unassigned local variable
}
推荐答案
编译器会在检测到未分配变量的可能性时生成该错误。因为 for
循环的主体不能保证执行(例如 for(int i = 1; i <0; i ++)
),该变量不会被视为无条件分配,因此会生成编译器错误。
The compiler will generate that error whenever it detects the possibility of an unassigned variable. Since the body of for
loops are not guaranteed to execute (e.g. for(int i = 1; i < 0; i++)
) the variable is not considered unconditionally assigned, and thus the compiler error is generated.
从文档:
C#编译器不允许使用未初始化变量。如果编译器检测到可能未初始化的变量的使用,则会生成编译器错误CS0165。有关详细信息,请参阅字段(C#编程指南)。请注意,当编译器遇到可能导致使用未分配变量的构造时,即使您的特定代码不存在,也会生成此错误。这避免了过度复杂的确定分配规则的必要性。
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 (C# Programming Guide). 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.
这篇关于“使用未分配的局部变量”错误,即使我分配变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!