考虑以下代码
这种行为有什么原因?我希望在这两种情况下都能得到相同的结果。
我做错了什么?
class Program
{
static void Main(string[] args)
{
string str;
int x;
for (x = 1; x < 10; x++)
{
str = "this";
}
Console.WriteLine(str);
Console.ReadLine();
}
}
当我编译时,出现以下错误:使用未赋值的本地变量“str”(我理解这部分)
如果我将for循环改为if,则可以正常工作。为什么会这样呢?(在这里感到困惑)
class Program
{
static void Main(string[] args)
{
string str;
int x;
if (true)
{
str = "this";
}
Console.WriteLine(str);
Console.ReadLine();
}
}
这种行为有什么原因?我希望在这两种情况下都能得到相同的结果。
我做错了什么?
for
循环是否一定会执行。这与任何人比其他人更聪明无关。 - dee-see