c#静态扩展方法,字典的克隆扩展方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CS扩展
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, int> myDic = new Dictionary<int, int>();
            myDic.Add(99, 56);
            myDic.Add(23, 11);

            Dictionary<int, int> tttdic = new Dictionary<int, int>();
            tttdic = myDic.Clone();

            Dictionary<int, int> xxxDic = new Dictionary<int, int>();
            xxxDic = myDic;

            myDic[99] = 5555555;
            Console.WriteLine(myDic[99]);
            Console.WriteLine(tttdic[99]);
            Console.WriteLine(xxxDic[99]);
            Console.ReadKey();
        }
    }

    public static class CSExtend
    {
        public static Dictionary<T, V> Clone<T, V>(this Dictionary<T, V> dictionary)
        {
            using (Stream objectStream = new MemoryStream())
       {

          //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制
          IFormatter formatter = new BinaryFormatter();
          formatter.Serialize(objectStream, dictionary);
          objectStream.Seek(0, SeekOrigin.Begin);
          return (Dictionary<T, V>)formatter.Deserialize(objectStream);

       }
} } }

c#静态扩展方法,字典的克隆扩展方法

这种方法是采用序列化反序列的克隆,是最靠谱的克隆,同样这种写法可以应用到类克隆,List克隆,都可以

参考文章:https://blog.csdn.net/alicehyxx/article/details/16118373

原方法:可自由修改

public static T Clone<T>(T RealObject)   
  
{   
     using (Stream objectStream = new MemoryStream())   
     {   
            //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制  
             IFormatter formatter = new BinaryFormatter();   
             formatter.Serialize(objectStream, RealObject);   
             objectStream.Seek(0, SeekOrigin.Begin);   
             return (T)formatter.Deserialize(objectStream);   
     }   
}  

 

 

===========================2018年3月23日15:08:49更新==================================

万能克隆扩展方法

    /// <summary>
    /// 深度克隆,字典和List可以直接.Clone,如果是类的话那个类必须得打上[Serializable]标签
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="RealObject"></param>
    /// <returns></returns>
    public static T Clone<T>(this T RealObject)
    {
        using (Stream objectStream = new MemoryStream())
        {
            //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制  
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(objectStream, RealObject);
            objectStream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(objectStream);
        }
    }

 

posted @ 2018-03-22 21:53  三页菌  阅读(265)  评论(0编辑  收藏  举报