我正在學習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 ");
}
}
}
}
謝謝:)
兩者對我來說都很好看......您是否使用過調試器?任何消息? – DrKoch 2015-02-10 06:13:32
什麼是例外(如果有的話)? – ziddarth 2015-02-10 06:14:24
使用下次調試.. – mybirthname 2015-02-10 06:16:53