C# clone an object with a new instance instead of reference
using System.Text.Json;
namespace a;
class Program
{
static void Main(string[] args)
{
var person = new Person
{
Id = 1,
Name = "Henry"
};
var person2 = person.DeepClone();
person2.Name = "Stark";
Console.WriteLine(person.Name);
Console.WriteLine(person2.Name);
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
public static class ObjectExtensions
{
public static T DeepClone<T>(this T obj)
{
var serialized = JsonSerializer.Serialize(obj);
return JsonSerializer.Deserialize<T>(serialized)!;
}
}
创建时间:1/11/2025 5:46:54 PM
修改时间:1/11/2025 5:47:12 PM