【代码笔记】【c#】克隆类对象(一般用于实体类)

        /// 
        /// 克隆类对象(一般用于实体类)
        /// 
        /// 
        public static void ClassClone(T clzOld, ref T clzNew)
        {
            clzNew = default(T);
            if (clzOld != null)
            {
                PropertyInfo[] piNew = clzNew.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                PropertyInfo[] piOld = clzOld.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

                if (piOld.Length > 0 && piNew.Length == piOld.Length) 
                {
                    for (Int32 i = 0; i < piOld.Length; i++)
                    {
                        if (piOld[i].PropertyType.IsValueType || piOld[i].PropertyType.Name.StartsWith("String"))
                        {
                            clzNew.GetType().GetProperty(piOld[i].Name).SetValue(clzNew, piOld[i].GetValue(clzOld, null), null);
                        }
                    }
                }
            }
        }

你可能感兴趣的:(c#,代码笔记)