[英]Use of unassigned local variable error for a assigned string
所以,我是 C# 的初学者,我真的不知道为什么我会为变量“名称”收到“使用未分配的局部变量错误”。 我有这个简单的代码要求输入姓名,如果不是 Bob 或 Alice,它会显示一条消息。
using System;
namespace exercise2
{
class Program
{
static void Main(string[] args)
{
string name;
int i = 0;
while (i == 0)
{
Console.Write("What is your name?\n>>> ");
name = Console.ReadLine();
if ((name == "Alice") || (name == "Bob"))
{
i = 1;
Console.Clear();
}
else
{
Console.WriteLine("You're not Alice or Bob.");
Console.ReadKey();
i = 0;
Console.Clear();
}
}
Console.WriteLine("Good Morning, " + name); //"name" is unassigned
Console.ReadKey();
}
}
}
希望这不是一个愚蠢的问题。
谢谢
这是因为编译器无法“看到”对while()
语句的评估肯定是true
,并且name
将第一次在while
块中分配。
改变你的
string name;
进入
string name = ""; //or string.Empty
尽管作为人类,我们可以很容易地读到 while 块将是第一次执行:
string name; //unassigned
int i = 0;
while (i == 0) //will enter
{
Console.Write("What is your name?\n>>> ");
name = Console.ReadLine(); //name will definitely be assigned here
... something else
}
Console.WriteLine("Good Morning, " + name); //compiler cannot "see" that the while loop will definitely be entered and name will be assigned. Therefore, "name" is unassigned
编译器看不到,因此给你错误。
或者,您也可以将while
块更改为do-while
以强制编译器查看将分配的name
(Credit goes to Lee ):
string name; //unassigned
int i = 0;
do //will enter
{
Console.Write("What is your name?\n>>> ");
name = Console.ReadLine(); //name will definitely be assigned here
... something else
} while (i == 0);
Console.WriteLine("Good Morning, " + name); //should be OK now
name 变量在可以使用的分支过程中的某个点未分配。 您可以为其分配一个默认值,但重构它是一个更好的解决方案。
在 while 循环内移动 name 变量以避免重新分配。 (从技术上讲,将它放在 while 循环中并不是重新分配同一个变量,因为当它再次循环时,会创建一个新变量并且之前的设置值不可用)。
将以下两行移动到条件的真实部分:
Console.WriteLine("Good Morning, " + name);
Console.ReadKey();
static void Main(string[] args)
{
int i = 0; //this should really be bool,
//because all you're doing is using 0 for repeat and 1 for stop.
while (i == 0)
{
Console.Write("What is your name?\n>>> ");
string name = Console.ReadLine();
if ((name == "Alice") || (name == "Bob"))
{
i = 1;
Console.Clear();
Console.WriteLine("Good Morning, " + name); //"name" is unassigned
Console.ReadKey();
}
else
{
Console.WriteLine("You're not Alice or Bob.");
Console.ReadKey();
i = 0;
Console.Clear();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.