c#小技巧3

來源:互聯網
上載者:User
1. 深拷貝與淺拷貝
深拷貝,對對象整體進行拷貝包括對象的值資料和引用到的對象。
淺拷貝,只拷貝對象的非靜態欄位,如實值型別資料。如果欄位為引用欄位那麼只拷貝引用,因此引用到的對象還是原來的對象。    // 這個標誌是必須的,告訴assembly該類可以序列化
    [Serializable]
    class Aphla
    {
        private string _name;
        private Beta _beta;

        public string Name
        {
            set { _name = value; }
            get { return _name; }
        }

        public string BetaName
        {
            set { _beta.Name = value; }
        }

        public Aphla(Beta b)
        {
            _beta = b;
        }

        public void Display(string objName)
        {
            Console.WriteLine("{0}, {1}", objName, _name);
            _beta.Display();
        }

        // 深拷貝對象
        public Aphla Clone()
        {
            Aphla a;
            // 建立流用於儲存要被序列化的對象
            MemoryStream ms = new MemoryStream();
            // 建立二進位格式器,用於對序列化對象的流進行格式化
            BinaryFormatter bf = new BinaryFormatter();

            // 將指定的對象以建立的格式器序列到流中
            bf.Serialize(ms, this);
            // 將流的遊標置回開始點
            ms.Position = 0;

            // 還原序列化流到對象
            a = (Aphla)bf.Deserialize(ms);
            return a;
        }

        // 淺拷貝對象
        public Aphla ShallowClone()
        {
            Aphla a = (Aphla)this.MemberwiseClone();
            return a;
        }
    }


    public class Beta
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public void Display()
        {
            Console.WriteLine("Beta: {0}", _name);
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.