欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c# 引用类型对象的深拷贝

程序员文章站 2023-11-30 11:59:16
c#中的对象大体分为值类型和引用类型,值类型大致包括 int, string, struct等,引用类型大致包括 自定义Class,object 等。 值类型直接存储对象,而引用类型存储对象的地址,在对引用类型进行复制的时候,也只是复制对象的地址。 完全复制一个引用类型对象主要有几种方法: 1.额外 ......

c#中的对象大体分为值类型和引用类型,值类型大致包括 int, string, struct等,引用类型大致包括 自定义Class,object 等。

值类型直接存储对象,而引用类型存储对象的地址,在对引用类型进行复制的时候,也只是复制对象的地址。

完全复制一个引用类型对象主要有几种方法:

1.额外添加一个构造函数,入参为待复制对象(如果字段为引用类型,需要继续添加构造函数,这样情况会变的十分复杂。)

    public class Test1
    {
        private int field1;
        private int field2;
        private int field3;
        public Test1()
        { 
        
        }

        public Test1(Test1 test1)
        {
            this.field1 = test1.field1;
            this.field2 = test1.field2;
            this.field3 = test1.field3;
        }
    }

2.利用序列化反序列化(对性能会有杀伤)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Test t1 = new Test();
            Console.WriteLine(t1.list.Count);
            Test t2 = (Test)Clone(t1);
            t2.list.Add("");
            Console.WriteLine(t2.list.Count);
            Console.WriteLine(t1.list.Count);
            Console.ReadLine();
        }

        public static object Clone(object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, obj);
            ms.Position = 0;
            return (bf.Deserialize(ms)); ;
        }
    }

    [Serializable]
    public class Test
    {
        public List<string> list = new List<string>();
    }
}

3.利用反射(测试了一个网上的接口可用,但是对性能杀伤和序列化反序列化相当,而且对代码混淆有一定影响。   https://www.cnblogs.com/zhili/p/DeepCopy.html)