• 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

  • 相关阅读:
    Eighth scrum meeting
    Seventh scrum meeting
    Sixth scrum meeting
    Fifth scrum meeting
    Forth scrum meeting
    Third scrum meeting
    2019-07-25 L430 生物 GPS
    L429 Why Do Smart People Do Foolish Things?
    L427 长难句
    L426
  • 原文地址:https://www.cnblogs.com/liaojinpiao/p/3204913.html
Copyright © 2020-2023  润新知