C#拷贝

using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;

namespace Zrr
{
    [Serializable]
    class Employee : ICloneable
    {
        public string IDCode { get; set; }
        public int Age { get; set; }
        public Deparment deparment {get; set; }

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        public Employee DeepClone()
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, this);
                objectStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as Employee;
            }
        }

        public Employee ShallowClone()
        {
            return this.Clone() as Employee;
        }
    }

    [Serializable]
    class Deparment
    {
        public string Name { get; set; }
        public override string ToString()
        {
            return this.Name;
        }
    }

    public class Myclass
    {
         //在Main线程中,语句的执行是从上到下的
        static void Main(string[] args)
        {
            Employee mike = new Employee() { IDCode = "NB123", Age = 30, deparment = new Deparment() { Name = "Dep1" } };
            Employee rose = mike.DeepClone() as Employee;
            Console.WriteLine(rose.IDCode);
            Console.WriteLine(rose.Age);
            Console.WriteLine(rose.deparment);

            Console.WriteLine("开始改变mike的值");
            mike.IDCode = "NB456";
            mike.Age = 60;
            mike.deparment.Name = "Dep2";

            Console.WriteLine(rose.IDCode);
            Console.WriteLine(rose.Age);
            Console.WriteLine(rose.deparment);

            Console.ReadKey();
        }
    }
}

 

posted @ 2019-11-07 19:57  曾日日  阅读(78)  评论(0)    收藏  举报