C#_deepCopy

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;

using System.Windows;



namespace ConsoleApplication1

{

    [Serializable]

    class Person

    {



        public Person()

        {

         

        }

        public int age { set; get; }

        public string name { set; get; }

   

    }

    class Program

    {

        public static Person deepCopy(Person value)

        {

            using (MemoryStream stream = new MemoryStream())

            { 

                BinaryFormatter  formattor = new BinaryFormatter();

                formattor.Serialize(stream,value);

                stream.Flush();

                stream.Seek(0,SeekOrigin.Begin);

                return  (Person)formattor.Deserialize(stream);

            }

        }

        static void Main(string[] args)

        {



            Person p1 = new Person();

            p1.age=20;

            p1.name = "aaa";



            Person p2 = new Person();

            p2.age = 20;

            p2.name = "aaa";

            //Console.WriteLine(p1==p2);

            //Console.WriteLine(p1.Equals(p2));



            Person p3 = deepCopy(p2);

            p2.age = 30;

            Console.WriteLine(p2.age);

            Console.WriteLine(p3.age);

             Console.ReadKey();



        }

    }

}

你可能感兴趣的:(copy)