当前位置: 移动技术网 > IT编程>开发语言>.net > c# 引用类型对象的深拷贝

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

2018年08月08日  | 移动技术网IT编程  | 我要评论

吴劲松,3d舞台,章萍

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)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网