小編給大家分享一下C#如何使用反射來實(shí)現(xiàn)對象的深度復(fù)制,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
實(shí)現(xiàn)方式
通過挨個(gè)羅列的方式一次復(fù)制子對象是非常耗費(fèi)人力的,如果子對象是引用類型,則還要需要考慮是否對子對象進(jìn)一步深拷貝。
實(shí)際應(yīng)用中,一個(gè)類如果有幾十個(gè)子對象,挨個(gè)復(fù)制對于開發(fā)人員來說索然無味比較費(fèi)時(shí)費(fèi)力。
所以使用反射機(jī)制來實(shí)現(xiàn)。
但是如果是服務(wù)端運(yùn)行的話,還是建議手動的實(shí)現(xiàn)。
畢竟反射機(jī)制比直接寫出來的效率要慢一些。
代碼:
public static class DeepCopyHelper { public static object Copy(this object obj) { Object targetDeepCopyObj; Type targetType = obj.GetType(); //值類型 if (targetType.IsValueType == true) { targetDeepCopyObj = obj; } //引用類型 else { targetDeepCopyObj = System.Activator.CreateInstance(targetType); //創(chuàng)建引用對象 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection) { if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member; Object fieldValue = field.GetValue(obj); if (fieldValue is ICloneable) { field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone()); } else { field.SetValue(targetDeepCopyObj, Copy(fieldValue)); } } else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myProperty.GetSetMethod(false); if (info != null) { object propertyValue = myProperty.GetValue(obj, null); if (propertyValue is ICloneable) { myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null); } else { myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null); } } } } } return targetDeepCopyObj; } }
看完了這篇文章,相信你對“C#如何使用反射來實(shí)現(xiàn)對象的深度復(fù)制”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站chinadenli.net,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
網(wǎng)頁標(biāo)題:C#如何使用反射來實(shí)現(xiàn)對象的深度復(fù)制-創(chuàng)新互聯(lián)
網(wǎng)站地址:http://chinadenli.net/article16/jjcgg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、網(wǎng)頁設(shè)計(jì)公司、ChatGPT、網(wǎng)站制作、企業(yè)網(wǎng)站制作、網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容