/// Copy Propertys and Fileds /// 拷貝屬性值 /// </summary> /// <typeparam name="T">目標(biāo)對(duì)象</typeparam> /// <param name="source">原對(duì)象</param> /// <param name="target">目標(biāo)對(duì)象</param> public static void CopyToAll<T>(this object source, T target) where T : class { if (source == null) { return; } if (target == null) { throw new ApplicationException("target 未實(shí)例化,!"); } var properties = target.GetType().GetProperties(); foreach (var targetPro in properties) { try { //判斷源對(duì)象是否存在與目標(biāo)屬性名字對(duì)應(yīng)的源屬性 if (source.GetType().GetProperty(targetPro.Name) == null) { continue; } //數(shù)據(jù)類(lèi)型不相等 if (targetPro.PropertyType.FullName != source.GetType().GetProperty(targetPro.Name).PropertyType.FullName) { continue; } var propertyValue = source.GetType().GetProperty(targetPro.Name).GetValue(source, null); if (propertyValue != null) {
target.GetType().InvokeMember(targetPro.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue }); } } catch (Exception ex) { } } //返回所有公共字段 var targetFields = target.GetType().GetFields(); foreach (var filed in targetFields) { try { var tfield = source.GetType().GetField(filed.Name); if (null == tfield) { //如果源對(duì)象中不包含這個(gè)公共字段則不處理 continue; } //類(lèi)型不一致不處理 if (filed.FieldType.FullName != tfield.FieldType.FullName) { continue; } var fieldValue = tfield.GetValue(source); if (fieldValue != null) { target.GetType().InvokeMember(filed.Name, BindingFlags.SetField, null, target, new object[] { fieldValue }); } } catch (Exception ex) { } } }
|