且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

克隆列表< T>

更新时间:2022-05-15 15:32:16

您可以使用下面的code键使该列表的深层复制或任何其他对象支持序列化:

You can use the below code to make a deep copy of the list or any other object supporting serialization:

另外,你可以用任何版本的.NET框架从2.0版及以上,以及类似的技术可以应用(除去仿制药的使用量)和使用1.1​​以及

Also you can use this for any version of .NET framework from v 2.0 and above, and the similar technique can be applied (removing the usage of generics) and used in 1.1 as well

public static class GenericCopier<T>
{
    public static T DeepCopy(object objectToCopy)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, objectToCopy);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return (T) binaryFormatter.Deserialize(memoryStream);
        }
    }
}

您可以通过调用它

List<int> deepCopiedList = GenericCopier<List<int>>.DeepCopy(originalList);

全部code来测试,如果这个工程:

Full code to test if this works:

static void Main(string[] args)
{
    List<int> originalList = new List<int>(5);
    Random random = new Random();
    for(int i = 0; i < 5; i++)
    {
        originalList.Add(random.Next(1, 100));
        Console.WriteLine("List[{0}] = {1}", i, originalList[i]);
    }
    List<int> deepCopiedList = GenericCopier<List<int>>.DeepCopy(originalList);
    for (int i = 0; i < 5; i++)
        Console.WriteLine("deepCopiedList[{0}] value is {1}", i, deepCopiedList[i]);
}