深拷貝與淺拷貝接口

子類繼承拷貝父類,直接調用拷貝方法,子類需要序列化:

 


    [Serializable]
    public class Cloneable<T> : ICloneable
    {
        public object Clone()
        {
            return MemberwiseClone();
        }
        public T DeepClone()
        {
            using (Stream objs = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(objs, this);
                objs.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objs);
            }
        }
    }

調用:

    [Serializable]
    public class a: Cloneable<a>
    {
        public int num;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章