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);
                }
            }

  • 相关阅读:
    C#:新邮件监听及搜索
    PHPexcel导入数据的时候出现object解决方法
    selectpage选择订单的时候,订单数量和金额会动态改变
    三、变量的简述
    TP框架where条件和whereOr条件同时使用
    一.OS运行机制
    二.进制简述
    1.go语言入门
    C# Redis学习系列二:Redis基本设置
    C# Redis学习系列一:Redis的认识、下载、安装、使用
  • 原文地址:https://www.cnblogs.com/leon032/p/2144759.html
Copyright © 2011-2022 走看看