zoukankan      html  css  js  c++  java
  • Object_Clone

            private object CloneObject(object o)
            {
                Type t = o.GetType();
                PropertyInfo[] properties = t.GetProperties();

                Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);

                foreach (PropertyInfo pi in properties)
                {
                    if (pi.CanWrite)
                    {
                        pi.SetValue(p, pi.GetValue(o, null), null);
                    }
                }

                return p;
            }

    还有一种方式,可以利用运行时序列化来deep clone.(前提是该object一定是Serializable的)

    static object DeepClone(object original)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Context=new StreamingContext(StreamingContextStates.Clone);
                    // Serialize the original object to memory
                    formatter.Serialize(stream, original);

                    stream.Position = 0;
                    // Deserialize memory stream to a new copy object
                    return formatter.Deserialize(stream);
                }
            }

  • 相关阅读:
    第三方包源码maven 下载
    Redis实现主从复制(转)
    Linq的优缺点
    async & await (转载)
    [转]抽象类与接口的区别及应用
    转载:C#中的泛型
    MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult
    C#中委托
    创建新的虚拟机
    GitHub上整理的一些工具[转载]
  • 原文地址:https://www.cnblogs.com/leon032/p/2144759.html
Copyright © 2011-2022 走看看