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

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

    //测试4:深度复制 TextBox
   


 try
 {
  Console.WriteLine("=== 深度复制 TextBox ===");
  txtTest.Text = "1234";
  Console.WriteLine("复制前:" + txtTest.Text);
  TextBox txtTmp = new TextBox();
  txtTmp = (TextBox)DataManHelper.DeepCopyObject(txtTest);
  Console.WriteLine("复制后:" + txtTmp.Text);
 }
 catch (Exception ex)
 {
  Console.WriteLine(ex.ToString());
 }

    //测试5:深度复制 DataGridView
 


 try
 {
  Console.WriteLine("=== 深度复制 DataGridView ===");
  DataGridView dgvTmp = new DataGridView();
  dgvTmp = (DataGridView)DataManHelper.DeepCopyObject(dgvTest);
 }
 catch (Exception ex)
 {
  Console.WriteLine(ex.ToString());
 }
}

其中txtTest是一个测试用的TextBox,dgvTmp是一个测试用的DataGridView,TestClass是一个自定义类,TestClassWithS是添加了Serializable特性的TestClass类,它们的具体实现如下:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataCopyTest
{
 public class TestClass
 {
  public int a;
  public string b;
  public string[] c;
  public TestClass d;
  public override string ToString()
  {
   string s = "a:" + a + "n";
   if (b != null)
   {
    s += "b:" + b + "n";
   }
   if (c != null)
   {
    foreach (string tmps in c)
    {
     if (!string.IsNullOrWhiteSpace(tmps))
     {
      s += "c:" + tmps + "n";
     }
    }
   }
   if (d != null)
   {
    s += d.ToString();
   }
   return s;
  }
 }

 //支持序列化的TestClass
 [Serializable]
 public class TestClassWithS
 {
  public int a;
  public string b;
  public string[] c;
  public TestClassWithS d;
  public override string ToString()
  {
   string s = "a:" + a + "n";
   if (b != null)
   {
    s += "b:" + b + "n";
   }
   if (c != null)
   {
    foreach (string tmps in c)
    {
     if (!string.IsNullOrWhiteSpace(tmps))
     {
      s += "c:" + tmps + "n";
     }
    }
   }
   if (d != null)
   {
    s += d.ToString();
   }
   return s;
  }
 }
}

我对每个搜来的深复制方法,都用了这五个类的实例进行深复制测试,这五个类的特征如下:

I、对自定义类TestClass进行深复制测试

II、对自定义类TestClassWithS进行深复制测试,TestClassWithS是添加了Serializable特性的TestClass类

III、对DataTable进行深复制测试

IV、对控件TextBox进行深复制测试

V、对控件DataGridView进行深复制测试

我们通过实现方法DataManHelper.DeepCopyObject来进行测试

测试深复制方法1

使用二进制流的序列化与反序列化深度复制对象


public static object DeepCopyObject(object obj)
{
 BinaryFormatter Formatter = new BinaryFormatter(null, 
  new StreamingContext(StreamingContextStates.Clone));
 MemoryStream stream = new MemoryStream();
 Formatter.Serialize(stream, obj);
 stream.Position = 0;
 object clonedObj = Formatter.Deserialize(stream);
 stream.Close();
 return clonedObj;
}