.NET的深复制方法(以C#语言为例)

2019-12-30 14:21:19于海丽

   在 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
   在 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph)
   在 DataCopyTest.DataManHelper.DeepCopyObject(Object obj) 位置 d:MyProgramsDataCopyTestDataCopyTestDataManHelper.cs:行号 24
   在 DataCopyTest.FormMain.FormMain_Load(Object sender, EventArgs e) 位置 d:MyProgramsDataCopyTestDataCopyTestFormMain.cs:行号 141
结论:利用序列化与反序列化到二进制流的方法深复制对象,只有在该对象支持Serializable特性时才可使用

测试深复制方法2


public static object DeepCopyObject(object obj)
{
 Type t = obj.GetType();
 PropertyInfo[] properties = t.GetProperties();
 Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, obj, null);
 foreach (PropertyInfo pi in properties)
 {
  if (pi.CanWrite)
  {
   object value = pi.GetValue(obj, null);
   pi.SetValue(p, value, null);
  }
 }
 return p;
}

五个场景的测试结果为:

I、不会触发异常,但结果完全错误

II、不会触发异常,但结果完全错误

III、不会触发异常,但结果完全错误

IV、Text字段赋值结果正确,但其他内容不能保证

V、触发异常ArgumentOutOfRangeException、TargetInvocationException

“System.ArgumentOutOfRangeException”类型的第一次机会异常在 System.Windows.Forms.dll 中发生
“System.Reflection.TargetInvocationException”类型的第一次机会异常在 mscorlib.dll 中发生
System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> System.ArgumentOutOfRangeException: 指定的参数已超出有效值的范围。
参数名: value
   在 System.Windows.Forms.DataGridView.set_FirstDisplayedScrollingColumnIndex(Int32 value)
   --- 内部异常堆栈跟踪的结尾 ---
   在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   在 System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   在 System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   在 System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   在 DataCopyTest.DataManHelper.DeepCopyObject(Object obj) 位置 d:MyProgramsDataCopyTestDataCopyTestDataManHelper.cs:行号 29