簡體   English   中英

如何在派生類對象內為基類屬性賦值而不一一列出?

[英]How to assign values base class properties inside a derived class object without listing them one by one?

在以下情況下,我無法控制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; 
}

您應該使用反射。 像這樣在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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM