c# 父类与子类互转的两种方法

子类继承父类后,拓展了一些新属性,想在不同业务场景里使用,就必须经过转换,常见的转换方式有序列化,反射以及mapper

先介绍父类和子类:

/// <summary>
/// People类-父类
/// </summary>
public class People
{
    /// <summary>
    /// sex
    /// </summary>
    public string sex{ get; set; }

    /// <summary>
    /// 年龄
    /// </summary>
    public int age{ get; set; }
}

/// <summary>
/// Student-子类
/// </summary>
public class Student:People
{
    /// <summary>
    /// 学校
    /// </summary>
    public string school{ get; set; }

    /// <summary>
    /// 班级
    /// </summary>
    public int @class{ get; set; }
}  

先介绍一个父类向子类单向转的方法,此方法只能把父类转子类,相反是不可以的:

People people = new Student();
Student student = (Student)people;

接下介绍互转的方法,先来实例化两个类:

People people=new People();
Student student =new Student ();

重点来了,先介绍第一种,用反射的方法,它是把实体内所有元素进行转换:

  foreach (PropertyInfo item in typeof(People).GetProperties())
                        {
                            item.SetValue(student, item.GetValue(people));
                        }

第二种,用mapper,现有的mapper类有很多,我用的是emitmapper可以在nuget上搜到

ObjectsMapper<People, Student> mapper = ObjectMapperManager.DefaultInstance.GetMapper<People, Student>();
student=mapper.Map(people);

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值