推荐使用 ,一个开源的深拷贝的类库, 不用自己实现了, 安全高效,测试了一下简单的10万次, 也能在1秒之内
https://github.com/force-net/DeepCloner
Install-Package DeepCloner
Usage
Deep cloning any object:
var clone = new { Id = 1, Name = "222" }.DeepClone();
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
public static class DeepCloner
{
public static T DeepClone<T>(this T source)
{
if (ReferenceEquals(source, null))
return default;
return (T)DeepClone((object)source);
}
private static object DeepClone(object source)
{
if (source == null)
return null;
Type type = source.GetType();
if (type.IsPrimitive || type == typeof(string))
{
return source;
}
else if (type.IsArray)
{
Type elementType = type.GetElementType();
var array = source as Array;
var copied = Array.CreateInstance(elementType, array.Length);
for (int i = 0; i < array.Length; i++)
{
copied.SetValue(DeepClone(array.GetValue(i)), i);
}
return copied;
}
else if (typeof(IList).IsAssignableFrom(type))
{
Type itemType = type.GetGenericArguments()[0];
var collection = Activator.CreateInstance(type) as IList;
var list = source as IList;
foreach (var item in list)
{
collection.Add(DeepClone(item));
}
return collection;
}
else
{
var clone = Activator.CreateInstance(type);
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
if (property.CanRead && property.CanWrite)
{
var value = property.GetValue(source);
property.SetValue(clone, DeepClone(value));
}
}
return clone;
}
}
}
public class TestClass
{
public string Name { get; set; }
public List<int> Numbers { get; set; }
public NestedClass Nested { get; set; }
}
public class NestedClass
{
public int Id { get; set; }
public string Description { get; set; }
}
// Example usage
public class Program
{
public static void Main(string[] args)
{
var original = new TestClass
{
Name = "Original",
Numbers = new List<int> { 1, 2, 3 },
Nested = new NestedClass { Id = 1, Description = "Nested" }
};
var clone = original.DeepClone();
// Test the clone
clone.Name = "Clone";
clone.Numbers[0] = 42;
clone.Nested.Id = 2;
Console.WriteLine(original.Name); // Output: Original
Console.WriteLine(original.Numbers[0]); // Output: 1
Console.WriteLine(original.Nested.Id); // Output: 1
}
}
大佬你好,熬夜搞了一波,终于把所有字段都改完了,现在全部是属性了。
但克隆到一半,还是弹出了:
System.ArgumentException:“Object of type 'System.Object' cannot be converted to type
这个报错。
这个报错不应该是字段无法转成对应类型的报错吗?可是我已经把所有字段都修改成属性了啊。
我在百度搜不到解决办法,只能再来问问大佬。