QHMG

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

浅度复制 

// See https://aka.ms/new-console-template for more information
//Console.WriteLine("Hello, World!"); 2024.3.4
using System;
using System.Collections.Generic;
using System.Text;
namespace shallowCopyDemo1
{
    public class Content
    {
        public int Val;
    }
    public class Cloner
    {
        public Content MyContent = new Content();
        public Cloner(int newVal)
        {
            MyContent.Val = newVal;
        }
        public object GetCopy()
        {
            return MemberwiseClone();
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            Cloner mySource = new Cloner(5);
            Cloner myTarget = (Cloner)mySource.GetCopy();
            Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
            mySource.MyContent.Val = 2;
            Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
            Console.ReadKey();
        }
    }
}
/*
MyTarget.MyContent.val = 5
MyTarget.MyContent.val = 2 
 */

深度复制

// See https://aka.ms/new-console-template for more information
//Console.WriteLine("Hello, World!"); 2024.3.4
using System;
using System.Collections.Generic;
using System.Text;
namespace DeepCopyDemo01
{
    public class Content
    {
       public int Val;
    }
    public class Cloner : ICloneable
    {
        public Content MyContent = new Content();
        public Cloner(int newVal)
        {
            MyContent.Val = newVal;
        }
        public object GetCopy()
        { 
            return MemberwiseClone();
        }
        #region ICloneable 成员
        public object Clone()
        {
            Cloner clonedCloner = new Cloner(MyContent.Val);
            return clonedCloner;
        }
        #endregion
    }
    public class Program
    {
        static void Main(string[] args)
        {
            Cloner mySource = new Cloner(5);
            Cloner myTarget = (Cloner)mySource.Clone();
            Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
            mySource.MyContent.Val = 2;
            Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
            Console.ReadKey();
        }
    }
}
/*
MyTarget.MyContent.val = 5
MyTarget.MyContent.val = 5 
 */

 

posted on 2024-03-04 13:33  强化闷棍  阅读(1)  评论(0编辑  收藏  举报