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

  • 相关阅读:
    HDU5090模拟,hash
    在Android手机上获取其它应用的包名及版本
    ubunut在系统恢复模式下无法改动rootpassword的分析和解决
    Index column size too large. The maximum column size is 767 bytes.
    java实现定时任务
    APP账号密码传输安全分析
    用RSA加密实现Web登录密码加密传输
    svn is already locked解决方案
    ajax跨域请求
    redis+spring配置
  • 原文地址:https://www.cnblogs.com/leon032/p/2144759.html
Copyright © 2011-2022 走看看