gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:59:54 27 4
gpt4 key购买 nike

我有一个关于为 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/

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