“未分配局部变量的使用"即使我分配了变量也会出错? [英] "Use of unassigned local variable" error even though I assign the variable?

查看:27
本文介绍了“未分配局部变量的使用"即使我分配了变量也会出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,编译器生成错误使用未分配的局部变量 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            
}

推荐答案

每当编译器检测到未赋值的变量可能时,就会生成该错误.

The compiler generates that error whenever it detects an unassigned variable is possible.

因为 for 循环的主体不能保证执行——例如,for(int i = 123; i < 0; i++)——变量是不能保证被赋值,所以编译器会产生错误.

Because the body of for loops are not guaranteed to execute—for example, for(int i = 123; i < 0; i++)—the variable is not guaranteed to be assigned, and so the compiler generates the error.

来自文档:

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屋!

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