• C#整理——深浅度复制


    一:浅度复制(新对象的引用成员指向源对象中相同引用成员的对象,即另个不同对象的相同类型的引用指向同一个对象):

    如:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication13
    {
        public class Content
        {
            public int Val2;
        }
    
        public class Cloner
        {
            public int Val;
            public Content Mycontent = new Content();//这是引用类型的字段,可以进行浅复制;
            public Cloner(int newVal)
           {
               Mycontent.Val2 = newVal;
               Val=newVal;  //Val不是引用类型而是值类型,所以不能进行浅复制,就算进行了也无效;
           }
            public object GetCopy()
            {
                return MemberwiseClone();
            }
        }
        class Tester
        {
            static void Main(string[] args)
            {
                Cloner source = new Cloner(5);
                Cloner target = (Cloner)source.GetCopy();
                Console.WriteLine("{0},{1}",target.Val,target.Mycontent.Val2);
                source.Mycontent.Val2 = 8;
                Console.WriteLine("{0},{1}", target.Val, target.Mycontent.Val2);
                Console.ReadKey();
            }
        }
    
    }

    结果:5,5

            5,8

    二:深复制(进行深复制的类要实习ICloneable接口)(理解:同一个类的不同对象的相同类型的引用之间只是完成了由一方给另一方赋值,这两个引用并没有指向同一对象)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication13
    {
        public class Content
        {
            public int Val2;
        }
    
        public class Cloner:ICloneable
        {
            public int Val;
            public Content Mycontent = new Content();
            public Cloner(int newVal)
           {
               Mycontent.Val2 = newVal;
               Val=newVal;  
           }
            public object Clone()
            {
                Cloner clonedCloner = new Cloner(Mycontent.Val2);
                 return clonedCloner;
            }
        }
        class Tester
        {
            static void Main(string[] args)
            {
                Cloner source = new Cloner(5);
                Cloner target = (Cloner)source.Clone();
                Console.WriteLine("{0},{1}",target.Val,target.Mycontent.Val2);
                source.Mycontent.Val2 = 8;
                Console.WriteLine("{0},{1}", target.Val, target.Mycontent.Val2);
                Console.ReadKey();
            }
        }
    
    }

    结果:5,5

           5,5

  • 相关阅读:
    .NET Core MVC下的TagHelper
    测试.NET core MiddleWare 运行逻辑
    中台
    VSCode 完美整合前后端框架(angular2+.NET core)
    三分钟热度并非贬义
    【算法】莫队算法粗略讲解
    【题解】洋溢着希望
    【三角学】三角恒等变换公式推导
    【题解】方差
    【数据结构】FHQ Treap 详解
  • 原文地址:https://www.cnblogs.com/liaojinpiao/p/3204913.html
Copyright © 2020-2023  润新知