C# Copy an object by value
This question already has an answer here:
There is a much simpler way of cloning an object to another by using JSON serializer. This trick requires no modification or implementation of interfaces on the cloned class, just a JSON serializer like JSON.NET.
public static T Clone<T>(T source)
{
var serialized = JsonConvert.SerializeObject(source);
return JsonConvert.DeserializeObject<T>(serialized);
}
您可以使用此扩展方法来复制所有对象字段和属性。当您尝试复制作为引用类型的字段和属性时可能会出现一些错误。
public static T CopyObject<T>(this T obj) where T : new()
{
var type = obj.GetType();
var props = type.GetProperties();
var fields = type.GetFields();
var copyObj = new T();
foreach (var item in props)
{
item.SetValue(copyObj, item.GetValue(obj));
}
foreach (var item in fields)
{
item.SetValue(copyObj, item.GetValue(obj));
}
return copyObj;
}
链接地址: http://www.djcxy.com/p/40772.html
上一篇: .NET中是否存在Object1.CopyTo(Object2)方法?
下一篇: C#按值复制一个对象