2016-03-01 63 views
2

因此,我是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(); 
     } 
    } 
} 

希望这不是一个愚蠢的问题。

感谢

回答

2

这是因为编译器不能“看到”上while()声明评价肯定会truename将在while块的第一次分配。

更改

string name; 

string name = ""; //or string.Empty 

虽然作为人,我们可以读出轻松的,而块将会首次被执行:

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 

编译器无法看到,从而给你错误。

或者,您也可以改变whiledo-while强制编译器看到,name将被分配(幸得Lee):

​​
+3

改变环路成'不要while'也应该工作。 – Lee

+0

@Lee更新并记入你...;) – Ian

+0

谢谢!这工作。我不明白的是,离开while模块的唯一方法不仅是当它是真的,这意味着名称将被分配?如果这是有道理的 – lfsando

1

名变量是在一些点未分配可以使用的分支过程。你可以给它分配一个默认值,但重构它是一个更好的解决方案。

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

     } 

    } 
} 
相关问题