2015-02-10 157 views
0

我正在學習C#並嘗試使用不同的方法添加到列表中。我嘗試了兩種不同的方法。第一個不工作,第二個一個工作使用構造函數C將項添加到列表中#

第一種方法有什麼問題?

class Program 
    { 
     static void Main(string[] args) 
     { 
      Employee emps = new Employee(); 
      emps.PromoteEmp(emps.emp); 
     } 
    } 

    class Employee 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public int Salary { get; set; } 
     public int Experience { get; set; } 
     public List<Employee> emp; 

     public Employee() 
     { 
      emp = new List<Employee>(); 
      emp.Add(new Employee() { ID = 1, Name = "A", Experience = 6, Salary = 30000 }); 
      emp.Add(new Employee() { ID = 2, Name = "B", Experience = 4, Salary = 10000 }); 
      emp.Add(new Employee() { ID = 1, Name = "C", Experience = 5, Salary = 15000 }); 
      emp.Add(new Employee() { ID = 1, Name = "D", Experience = 8, Salary = 60000 }); 
     } 

     public void PromoteEmp(List<Employee> empList) 
     { 
      foreach (Employee item in empList) 
      { 
       if (item.Experience > 5) 
       { 
        Console.WriteLine(item.Name + " promoted "); 
       } 
      } 
     } 
    } 

第二種方法

class Program 
    { 
     static void Main(string[] args) 
     { 
      Employee emps = new Employee(); 
      emps.AddToList(); 
      emps.PromoteEmp(emps.emp); 
     } 
    } 

    class Employee 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public int Salary { get; set; } 
     public int Experience { get; set; } 
     public List<Employee> emp; 


     public void AddToList() 
     { 
      emp = new List<Employee>(); 
      emp.Add(new Employee() { ID = 1, Name = "A", Experience = 6, Salary = 30000 }); 
      emp.Add(new Employee() { ID = 2, Name = "B", Experience = 4, Salary = 10000 }); 
     emp.Add(new Employee() { ID = 1, Name = "C", Experience = 5, Salary = 15000 }); 
     emp.Add(new Employee() { ID = 1, Name = "D", Experience = 8, Salary = 60000 }); 
     } 

     public void PromoteEmp(List<Employee> empList) 
     { 
      foreach (Employee item in empList) 
      { 
       if (item.Experience > 5) 
       { 
        Console.WriteLine(item.Name + " promoted "); 
       } 
      } 
     } 
    } 

謝謝:)

+0

兩者對我來說都很好看......您是否使用過調試器?任何消息? – DrKoch 2015-02-10 06:13:32

+0

什麼是例外(如果有的話)? – ziddarth 2015-02-10 06:14:24

+0

使用下次調試.. – mybirthname 2015-02-10 06:16:53

回答

1

很容易,在第一種情況下,您構建的Employee構成更多Employee s等等。

事實上,如果您打算粘貼您獲得的例外,那很明顯:StackOverflowException

+0

是的,這是我得到的例外。什麼是解決它?謝謝:) – Richa 2015-02-10 06:15:30

+0

刪除你寫的所有內容,員工持有員工名單是沒有意義的。想想你的意思是什麼模型,如果你需要寫在白板上,然後重新開始。 – Blindy 2015-02-10 06:16:17

+0

所以第二種方法很好?我可以這樣做嗎? – Richa 2015-02-10 06:19:16

0

你的第一個代碼導致無限循環,你在構造函數中添加同一類員工 。

+0

如何解決它?我不能在構造函數列表中的項目? – Richa 2015-02-10 06:14:30

0

其實,程序會在構造函數中無限循環並且永遠不會完成。

在main():

從該品系:僱員的emps =新員工();

程序轉到構造函數初始化對象。

現在,在構造:

emp.Add(新員工(){ID = 1,名稱= 「A」,經驗= 6,工資= 30000});

在這一行,您將添加新的Employee對象列表。這裏再次對象初始化,從而程序在構造函數中進入無限循環。

你的程序永遠不會到達最後一行。

相關問題