C#复制对象

        public static 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)
                {
                    object value = pi.GetValue(o, null);
                    pi.SetValue(p, value, null);
                }
            }
            return p;
        }



        public static void  CloneObject(Employee a,ref Employee_Log b)
        {
            try
            {
                var Types = a.GetType();//获得类型
                var Typed = typeof(Takeda_Employee_Log);
                foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段
                {
                    foreach (PropertyInfo dp in Typed.GetProperties())
                    {
                        if (dp.Name == sp.Name)//判断两对象属性名是否相同
                        {
                            dp.SetValue(b, sp.GetValue(a, null), null);//获得a对象属性的值复制给b对象的属性
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

posted @ 2022-05-30 17:20  highlightyys  阅读(18)  评论(0编辑  收藏  举报