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(, );
myDic.Add(, ); Dictionary<int, int> tttdic = new Dictionary<int, int>();
tttdic = myDic.Clone(); Dictionary<int, int> xxxDic = new Dictionary<int, int>();
xxxDic = myDic; myDic[] = ;
Console.WriteLine(myDic[]);
Console.WriteLine(tttdic[]);
Console.WriteLine(xxxDic[]);
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(, 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(, SeekOrigin.Begin);
return (T)formatter.Deserialize(objectStream);
}
}
上一篇:WPF学习之路由事件


下一篇:JS网站广告实现侧边栏滚动至div顶部后固定、鼠标滚动下拉侧边栏DIV固定