c# - 使用未分配的变量 - for 循环

标签 c#

我有一个关于为 for 循环内的变量赋值的问题。据我所知,如 Microsoft 所述,当有任何可能读取尚未分配的变量时,编译器会给出此错误消息。

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.

我的代码是这样的:

static void Main(string[] args)
{
    int i;

    for (int j = 0; j <= 5; j++)
    {
        i = j;
    }

    Console.WriteLine(i.ToString());

    Console.ReadLine();
}

我假设即使在这种特定情况下 i 将被分配,编译器也不会检查 for 语句中的实际条件,这意味着它会处理

for (int j = 0; j <= -1; j++)

一样吗?

最佳答案

由于您在 for 循环内为变量 i 赋值,编译器不够智能,无法查看它是否会被赋值,因此会出现错误。

一个简单的解决方案是为您的变量分配一些默认值。

int i = 0;

尽管从循环变量值看来控件将进入for 循环,但编译器无法确定这一点。

错误的原因是因为语言规范,

5.3 Definite assignment

At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by static flow analysis, that the variable has been automatically initialized or has been the target of at least one assignment.

评估条件不是静态流程,它会在运行时确定。因此,编译器无法确定 i 是否会被赋予任何值。

关于c# - 使用未分配的变量 - for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21440365/

相关文章:

c# - WPF 性能缓慢的原因

c# - Iphone,从 MonoTouch 获取国家列表

c# - CaSTLe DynamicProxy 接口(interface)代理生成

c# - .jar 和 .dll 文件之间的区别

c# - Tag Helpers 在 ViewComponent 中没有正确呈现

c# - System.DllNotFoundException :/system/lib/libsqlite. 所以

c# - 从 C# 中具有相同主键的两个表中获取不同的列值

c# - 无法分配给 'method',因为它是一个“方法组”

C# 在 Release 模式下运行时是否会编译出 Debug 语句?

c# - 在 foreach 循环内设置用户控件的属性