簡體   English   中英

C#將相同的屬性從派生類克隆到基類

[英]C# Clone same properties from Derived class to base class

我正在努力尋找一種將相同屬性從派生類克隆到基類的安全方法,我已經有一種方法,將基類屬性克隆到派生類

protected internal void InitInhertedProperties(object baseClassInstance)
    {
        foreach (PropertyInfo propertyInfo in baseClassInstance.GetType().GetProperties())
        {
            object value = propertyInfo.GetValue(baseClassInstance, null);
            if (null != value) propertyInfo.SetValue(this, value, null);
        }
    }

但是反向克隆呢? 使用方法或庫將派生類的相同屬性克隆到基類的相同屬性。

基類

public class UserEntity
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }
    public int employee_id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string email { get; set; }
    public string login_id { get; set; }
    public string login_password { get; set; }
    public int role { get; set; }
    public bool is_delete { get; set; }
}

派生類

public class UserModel : UserEntity
{

    protected internal void InitInhertedProperties(object baseClassInstance)
    {
        foreach (PropertyInfo propertyInfo in baseClassInstance.GetType().GetProperties())
        {
            object value = propertyInfo.GetValue(baseClassInstance, null);
            if (null != value) propertyInfo.SetValue(this, value, null);
        }
    }
}

代替下面的方法:

var user_entity = new UserEntity();
        user_entity.id = user_model.id;
        user_entity.employee_id = user_model.employee_id;
        user_entity.first_name = user_model.first_name;
        user_entity.email = user_model.email;
        user_entity.login_id = user_model.login_id;
        user_entity.login_password = user_model.login_password;
        user_entity.role = user_model.role;
        user_entity.is_delete = false;

謝謝 !

public class UserEntity
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }
    public int employee_id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string email { get; set; }
    public string login_id { get; set; }
    public string login_password { get; set; }
    public int role { get; set; }
    public bool is_delete { get; set; }

    public UserEntity()
    {
    }

    public UserEntity(UserEntity userEntity)
    {
        this.id = userEntity.id;
        this.employee_id = userEntity.employee_id;
        this.first_name = userEntity.first_name;
        this.email = userEntity.email;
        this.login_id = userEntity.login_id;
        this.login_password = userEntity.login_password;
        this.role = userEntity.role;
        this.is_delete = false;
    }
}

public class UserModel : UserEntity
{
    public UserModel(UserEntity userEntity) : base(userEntity)
    {
    }
}

暫無
暫無

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

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