2011-03-10 27 views
0

如何使用C#中的遞歸將值賦給一組變量?在C#中使用遞歸爲一組變量賦值?

我可以很容易地做到這一點,但我不知道如何使用遞歸來做到這一點。

public void Assign() 
{ 
Console.Write("Name: "); 
Name = Console.ReadLine(); 

Console.Write("e-mail: "); 
Email = Console.ReadLine(); 

Console.Write("Phone Number: "); 
Phone = int.Parse(Console.ReadLine()); 
} 

感謝您的幫助。

+2

我沒有跟着這個問題......你爲什麼要使用這個遞歸? – RQDQ 2011-03-10 20:27:57

+0

聞起來像家庭作業! – 2011-03-10 20:28:40

+0

如果這是一項家庭作業,然後相應標記並閱讀如何發佈作業問題:http://stackoverflow.com/tags/homework/info – 2011-03-10 20:28:42

回答

0

如果你要使用遞歸,你必須有足夠的本地上下文來完成你要在你的函數中做的任何工作,並且你必須知道何時/何地停止(並開始彈出你的堆棧)。

你的例子看起來像(如果有的話)循環。

0

你的問題似乎是作業,因爲教科書通常使用這種可怕的問題來教授遞歸。

namespace Homework 
{ 
    class Recursion 
    { 
     static string[] nameList = new string[5]; 
     static void Main(string[] args) 
     { 
      AssignNames(0); 
      Console.WriteLine("The names are:"); 
      foreach(string name in nameList) 
      { 
       Console.WriteLine(name); 
      } 
      Console.ReadKey(); 

     } 

     static void AssignNames(int index) 
     { 
      if (index == nameList.Length) return; 
      Console.Write("Enter name #{0}: ", index + 1); 
      nameList[index] = Console.ReadLine(); 
      AssignNames(index + 1); 
     } 
    } 
}