我正在努力寻找一种安全的方法将相同的属性从派生类克隆到基类,我已经有了一个方法,将基类属性克隆到派生类
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;
谢谢!
答案 0 :(得分:0)
#include <stdio.h>
int main() {
/* initilize variables (area, width and height) */
float area, width, height;
/* assign variables */
area = 0.0;
width = 0.0;
height = 0.0;
/* Gather user input */
printf("Enter the area in square metres\n");
scanf("%f", &area);
printf("Enter the width in square metres\n");
scanf("%f", &width);
/* Height of a rectangle = area/width */
height = area / width;
/* Print result */
printf("The height of the rectangle is: %f", height);
return 0;
}