复制对象

 

 

public class ObjectReflection
    {
        public static PropertyInfo[] GetPropertyInfos(Type type)
        {
            return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        }

        /// <summary>
        /// 将一个对象的属性给另一个对象的相同属性赋值
        /// </summary>
        /// <typeparam name="S">源对象类型</typeparam>
        /// <typeparam name="T">目标对象类型</typeparam>
        /// <param name="s">源对象</param>
        /// <param name="t">目标对</param>
        public static void AutoMapping<S, T>(S s, T t)
        {
            // get source PropertyInfos
            PropertyInfo[] pps = GetPropertyInfos(s.GetType());
            // get target type
            Type target = t.GetType();

            foreach (var pp in pps)
            {
                PropertyInfo targetPP = target.GetProperty(pp.Name);
                object value = pp.GetValue(s, null);

                if (targetPP != null && value != null)
                {
                    try
                    {
                        targetPP.SetValue(t, value, null);
                    }
                    catch (Exception)
                    {
                         
                    }
                   
                }
            }
        }
    }

  

posted @ 2017-09-13 19:42  人生为卒  阅读(115)  评论(0编辑  收藏  举报