An implementation of class replication based on reflection

  • 2020-05-10 18:41:01
  • OfStack

Suppose there is a class with the name EtyBase and another class with the name EtyTwo. EtyTwo inherits from EtyBase. Now, the traditional way to ask for the property values of EtyTwo to be copied from one EtyBase is


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

There are several downsides to this approach

When the property of       EtyBase changes, the property of the copy also has to change.
If       has more EtyBase properties, the copy method will be tedious and tedious to write.

 

If I do it with reflection, here's what I do


View Code 
  public void CopyEty(EtyBase from, EtyBase to)
  {
// Get class members using reflection 
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;
    }
}
  }

Reflection addresses both of these shortcomings, and this replication method does not need to change when class attributes are changed or added. This, of course, requires some operational efficiency.


Related articles: