对已分配的字符串使用未赋值的局部变量错误

本文关键字:赋值 局部变量 错误 分配 字符串 | 更新日期: 2023-09-27 18:36:52

所以,我是 C# 的初学者,我真的不知道为什么我对变量"name"出现"使用未分配的局部变量错误"。我有一个简单的代码,要求输入名称,如果不是鲍勃或爱丽丝,它会显示一条消息。

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(功劳归于 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 循环中并不是对同一变量的重新分配,因为当它再次循环时,会创建一个新变量并且之前的设置值不可用)。

将以下两行移动到条件的 true 部分:

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();
            }
        }
    }
}