源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

基于反射解决类复制的实现方法

  • 时间:2022-07-06 02:14 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:基于反射解决类复制的实现方法
假定一个类,类名是EtyBase,另一个类类名是EtyTwo,EtyTwo继承自EtyBase。现在要求EtyTwo的属性值从一个EtyBase中复制过来传统做法是
[u]复制代码[/u] 代码如下:
View Code   public void CopyEty(EtyBase from, EtyBase to)   { to.AccStatus = from.AccStatus; to.Alarm = from.Alarm; to.AlarmType = from.AlarmType; to.CarNum = from.CarNum; to.DevNum = from.DevNum; to.DeviceNum = from.DeviceNum; to.Direct = from.Direct; to.DriveCode = from.DriveCode; to.GpsData = from.GpsData; to.GpsEnvent = from.GpsEnvent; to.GpsOdo = from.GpsOdo; to.GpsSpeed = from.GpsSpeed; to.GpsStatus = from.GpsStatus; to.GpsrevTime = from.GpsrevTime; to.Gsmci = from.Gsmci; to.Gsmci1 = from.Gsmci1; to.Gsmloc = from.Gsmloc; to.Gsmloc1 = from.Gsmloc1; to.IsEffective = from.IsEffective; to.IsJump = from.IsJump; to.IsReply = from.IsReply; to.Latitude = from.Latitude; to.LaunchStatus = from.LaunchStatus; to.Longitude = from.Longitude; to.MsgContent = from.MsgContent; to.MsgExId = from.MsgExId; to.MsgId = from.MsgId; to.MsgLength = from.MsgLength; to.MsgType = from.MsgType; to.NowOverArea = from.NowOverArea; to.NowStatus = from.NowStatus; to.Oil = from.Oil; to.PulseCount = from.PulseCount; to.PulseOdo = from.PulseOdo; to.PulseSpeed = from.PulseSpeed; to.ReplyContent = from.ReplyContent; to.RevMsg = from.RevMsg; to.Speed = from.Speed; to.Status = from.Status; to.Temperture = from.Temperture; to.UserName = from.UserName;   }
[b]这样子做有几点不好的地方[/b]     EtyBase的属性改变时复制的属性也得改变,耦合较高;     若EtyBase的属性比较多,那么这个复制方法将显得比较冗长,写的人手累。   [b]如果用反射来做,我是这么做的 [/b]
[u]复制代码[/u] 代码如下:
View Code   public void CopyEty(EtyBase from, EtyBase to)   { //利用反射获得类成员 FieldInfo[] fieldFroms = from.GetType().GetFields(); FieldInfo[] fieldTos = to.GetType().GetFields(); int lenTo = fieldTos.Length; for (int i = 0, l = fieldFroms.Length; i < l; i++) {     for (int j = 0; j < lenTo; j++)     {   if (fieldTos[j].Name != fieldFroms[i].Name) continue;   fieldTos[j].SetValue(to, fieldFroms[i].GetValue(from));   break;     } }   }
反射可以解决上述的两个缺点,当类属性改变或增加时,此复制方法无需改变。当然这是要付出些许运行效率的。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部