代码改变世界

C#中=跟实现浅复制的区别

2015-05-20 10:38  STARSIX03  阅读(123)  评论(0编辑  收藏  举报
using System;

namespace Copy
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new B { Count = 1, Str = "Str", A = new A { AName = "AName" } };
            var b = new B { Count = 1, Str = "Str", A = new A { AName = "AName" } };
            var c = a;
            var d = b.Clone();
            a.Count = 2;
            a.Str = "XXX";
            a.A.AName = "VVV";
            b.Count = 2;
            b.Str = "XXX";
            b.A.AName = "VVV";
            Console.WriteLine(c.Count + ";" + c.Str + ";" + c.A.AName);
            Console.WriteLine(d.Count + ";" + d.Str + ";" + d.A.AName);
            Console.ReadLine();
        }
    }

    public class A
    {
        public string AName { get; set; }
    }

    public class B
    {
        public int Count { get; set; }

        public string Str { get; set; }

        public A A { get; set; }

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