关于自动实现的属性的问题C#

时间:2010-11-19 01:25:54

标签: c# refactoring

我有这段代码:

void Main()
{
    List<Employee> employeeList;

    employeeList = new List<Employee>
    {
        {new Employee("000001", "DELA CRUZ, JUAN T.")},
        {new Employee("000002", "GOMEZ, MAR B.")},
        {new Employee("000003", "RIVERA, ERWIN J.")}
    };

    employeeList.Dump();
}

public class Employee
{
    public string EmployeeNo { get; set; }
    public string Name { get; set; }

    public Employee(string employeeNo, string name)
    {
        this.EmployeeNo = employeeNo;
        this.Name = name;
    }   
}

如何仅使用属性创建Employee类的新实例,并将该实例添加到employeeList(我的意思是不使用employee的类构造函数)?

我已经提出了一个解决方案,但它太长了。我应该如何缩短它?

void Main()
{   
    List<Employee> employeeList;

    #region - I want to shorten these lengthy codes. 
    Employee employee1 = new Employee();
    employee1.EmployeeNo = "000001";
    employee1.Name = "DELA CRUZ, JUAN T.";

    Employee employee2 = new Employee();
    employee2.EmployeeNo = "000002";
    employee2.Name = "GOMEZ, MAR B.";
    // other employees...
    #endregion

    employeeList = new List<Employee>
    {
        employee1,
        employee2
    };

    employeeList.Dump();
}

public class Employee
{
    public string EmployeeNo { get; set; }
    public string Name { get; set; }    
}

3 个答案:

答案 0 :(得分:6)

你可以这样做

var list = new List<Employee> 
{
  new Employee {EmployeeNo = "000001", Name = "Peter Pan"}, 
  new Employee {EmployeeNo = "000002", Name = "King Kong"}
};

这个

public class EmployeeList : List<Employee>
{
    public void Add(string no, string name)
    {
        this.Add(new Employee(no, name));
    }
}

var list = new EmployeeList 
{ 
  { "000001", "Peter Pan" }, 
  { "000002", "King Kong"} 
};

答案 1 :(得分:0)

你可以做那样的事情

var employee1 = New Employee() { EmployeeNo = "000001", Name = "DELA CRUZ, JUAN T." };

答案 2 :(得分:0)

这个怎么样?

void Main()
{   
    var employeeList = new List<Employee> {
                            new Employee { EmployeeNo = "000001", Name = "DELA CRUZ, JUAN T." },
                            new Employee { EmployeeNo = "000002", Name = "GOMEZ, MAR B." }
                       };

    employeeList.Dump();
}

public class Employee
{
    public string EmployeeNo { get; set; }
    public string Name { get; set; }    
}