標籤:
使用ef,有時候會遇到,要對一個對象進行拷貝複製,可是一般的方法,拷貝後會提示此對象的執行個體在內容相關的 entitystate已經存在,就需要用一種拷貝。
簡單的拷貝只拷貝了實值型別,對參考型別的拷貝需要使用遞迴,依次迴圈到底。
public object Copy(object obj) { Object targetDeepCopyObj; try { Type targetType = obj.GetType(); //實值型別 if (targetType.IsValueType == true) { targetDeepCopyObj = obj; } //參考型別 else { targetDeepCopyObj = System.Activator.CreateInstance(targetType); //建立引用對象 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; } catch (Exception e) { } return null; }
c#深拷貝的一個方法