码迷,mamicode.com
首页 > Windows程序 > 详细

c#中类的深拷贝和浅拷贝

时间:2015-11-17 10:52:30      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

### 类的深拷贝和浅拷贝
1. 若要深拷贝,当前类和引用的类都需要支持序列化
2. 扩展类的拷贝
3. 代码示例
````C#    
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<DataTest> list = new List<DataTest>() { new DataTest() { i=1, str="2131" } };
            var list1 = list.Clone() as List<DataTest>;
            list[0].i = 2;
            list1[0].list[0].ii = 22;
        }
    }
    [Serializable]
    public class DataTest:ICloneable
    {
        public int i = 0;
        public string str = "";
        public List<DataTest1> list = new List<DataTest1>() { new DataTest1() { ii=2, strr="2313" } };
        public List<int> listi = new List<int>() { 1,2,3,4};
        public object Clone()
        {
            //返回浅拷贝
            //return MemberwiseClone() as DataTest;
            //返回深拷贝
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, this);
            memoryStream.Position = 0;
            return binaryFormatter.Deserialize(memoryStream) as DataTest;
        }
    }
    [Serializable]
    public class DataTest1
    {
        public int ii = 0;
        public string strr = "";
    }
    public static class Ex
    {
        public static IEnumerable<T> Clone<T>(this IEnumerable<T> listToClone) where T : ICloneable
        {
            return listToClone.Select(item => (T)item.Clone()).ToList();
        }
    }
}  
````    

c#中类的深拷贝和浅拷贝

标签:

原文地址:http://www.cnblogs.com/adswads/p/4970699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!