基于反射解決類復(fù)制的實現(xiàn)方法
假定一個類,類名是EtyBase,另一個類類名是EtyTwo,EtyTwo繼承自EtyBase?,F(xiàn)在要求EtyTwo的屬性值從一個EtyBase中復(fù)制過來傳統(tǒng)做法是
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的屬性改變時復(fù)制的屬性也得改變,耦合較高;
若EtyBase的屬性比較多,那么這個復(fù)制方法將顯得比較冗長,寫的人手累。
如果用反射來做,我是這么做的
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;
}
}
}
反射可以解決上述的兩個缺點,當類屬性改變或增加時,此復(fù)制方法無需改變。當然這是要付出些許運行效率的。
相關(guān)文章
Unity游戲開發(fā)中必備的設(shè)計模式之外觀模式詳解
外觀模式是一種結(jié)構(gòu)型設(shè)計模式,為復(fù)雜系統(tǒng)提供了簡單的接口,使得子系統(tǒng)間的通信更加簡潔和易于維護。在Unity游戲開發(fā)中,外觀模式可以幫助開發(fā)者更好地管理游戲?qū)ο蠛徒M件等復(fù)雜結(jié)構(gòu)2023-05-05
C# 數(shù)據(jù)庫鏈接字符串加密解密工具代碼詳解
本文通過代碼給大家介紹C# 數(shù)據(jù)庫鏈接字符串加密解密工具的相關(guān)知識,實現(xiàn)思路大概是使用兩個數(shù)對連接字符串進行加密,再用這兩個數(shù)進行解密,具體詳細代碼,大家參考下本文2018-05-05
Unity3D使用陀螺儀控制節(jié)點旋轉(zhuǎn)
這篇文章主要為大家詳細介紹了Unity3D使用陀螺儀控制節(jié)點旋轉(zhuǎn),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11

