如何在派生类对象中分配值基类属性而不逐一列出它们?

时间:2014-08-26 23:20:05

标签: c#

在以下场景中,我无法控制Employee类,但可以基于此派生类。有没有办法可以创建一个派生类对象列表,如下所示

public class Employee
{
    public int EmployeeID {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    // Other properties may be added here in future
    // I have no access to this base class to modify it 

}


public class EmployeeFormatted: Employee // inherit form base calss Employee
{
    public string FullName {get; set;}
}


public List<EmployeeFormatted> GetFormattedEmployeeList()
{
    //How to assign base class properties of the derived object without assgining them one by one ?

    //I managed to do this  as following

    List<Employee> employees = GetEmployeeFromSomwhere();

    List<EmployeeFormatted> formattedEmployeesList = new List<EmployeeFormatted>();
    foreach ( emp in employees)
    {
        formattedEmployeesList.Add( new EmployeeFormatted
                        { 
                        //assign the base class properties one by one
                        EmployeeID = emp.EmployeeID,    
                        EmployeeCode = emp.EmployeeCode,

                        --
                        --

                        //assign the property defined in the inherited class

                        FullName = FomratName(emp.FirstName, emp.LastName)
                        });
    }

    return formattedEmployeesList; 
}

1 个答案:

答案 0 :(得分:0)

你应该使用反射。在EmployeeFormatted中创建一个新的参数化构造函数,如下所示

public EmployeeFormatted(Employee em)
        {
            var emProps = em.GetType().GetProperties();
            foreach (var prop in emProps)
            {
                this.GetType().GetProperty(prop.Name).SetValue(this,prop.GetValue(em));
            }
            this.FullName = FomratName(em.FirstName, em.LastName);
        }