[英]Adding item to list using constructor 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 ");
}
}
}
}
謝謝 :)
很簡單,在第一種情況下,您構造了Employee
,而后者構造了更多Employee
,依此類推。
實際上,如果您不願意粘貼所獲得的異常,則顯而易見: StackOverflowException
。
您的第一個代碼會導致無限循環,因為要在Constructor中添加相同的Employee類。
實際上,程序在構造函數中進入無限循環,並且永遠不會完成。
在Main()中:
從這一行開始:Employee emps = new Employee();
程序轉到構造函數初始化對象。
現在在構造函數中:
emp.Add(new Employee(){ID = 1,名稱=“ A”,經驗= 6,工資= 30000});
在這一行,您要向列表添加新的Employee對象。 這里再次進行對象初始化,因此程序進入構造函數中的無限循環。
您的程序將永遠無法到達最后一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.