首页 > 编程 > C# > 正文

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

2020-01-24 03:22:44
字体:
来源:转载
供稿:网友

假定一个类,类名是EtyBase,另一个类类名是EtyTwo,EtyTwo继承自EtyBase。现在要求EtyTwo的属性值从一个EtyBase中复制过来传统做法是

复制代码 代码如下:

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;
  }


这样子做有几点不好的地方

    EtyBase的属性改变时复制的属性也得改变,耦合较高;
    若EtyBase的属性比较多,那么这个复制方法将显得比较冗长,写的人手累。

 

如果用反射来做,我是这么做的

复制代码 代码如下:

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;
    }
}
  }


反射可以解决上述的两个缺点,当类属性改变或增加时,此复制方法无需改变。当然这是要付出些许运行效率的。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表