C# 深拷贝

测试实体:

class Test
{
    public int Age { get; set; } = 1;
    public string Sex { get; set; } = "男";
    public Name Name { get; set; } = new Name() { Name_ = "周杰伦", Second = new Second() { Num = 1 } };
}
class Name
{
    public string Name_ { get; set; }
    public Second Second { get; set; }
}

class Second
{
    public int Num { get; set; }
}

测试:


public static T DeepCopy<T>(T obj)
{
    //如果是字符串或值类型则直接返回
    if (obj is string || obj.GetType().IsValueType) return obj;

    object retval = Activator.CreateInstance(obj.GetType());
    FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
    foreach (FieldInfo field in fields)
    {
        try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); }
        catch { }
    }
    return (T)retval;
}

static void Main()
{
    Test test = new Test();
    Console.WriteLine(test.Name.Second.Num);

    Test test1 = DeepCopy(test);
    test1.Name.Second.Num = 100;
    Console.WriteLine(test1.Name.Second.Num);
    Console.WriteLine(test.Name.Second.Num);

    Console.ReadKey();
}

输出:

1
100
1

可见,不影响之前的对象。

posted @ 2022-11-03 20:45  double64  阅读(68)  评论(0)    收藏  举报