c#实体转化

  经常会遇到把一个实体转化成另一个实体这样的情况,实体的属性一个一个手写去转化不反对,但不是啥好的方法;可以使用反射写一个通用的实体转化类,针对任何实体转化,不用再去自己手写。

  public static To ConvertObjectByEntity<T, To>(T entity)
        {
            if (entity == null)
            {
                return default(To);
            }
            Type type = typeof(To);
            To t = CreateInstance<To>(type.Assembly.FullName, type.FullName);
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
            

            foreach (PropertyInfo propertyInfo in type.GetProperties())
            {
                PropertyInfo tpropertyInfo = propertyInfos.Where(o => o.Name == propertyInfo.Name).FirstOrDefault();
                if (tpropertyInfo == null)
                {
                    continue;
                }
                object value = GetPropertyValue(entity, tpropertyInfo.Name);
                if (value == null)
                {
                    continue;
                }
                propertyInfo.SetValue(t, value, null);

            }
            return t;
        }

 

posted @ 2016-07-13 10:59  .追风逐月  阅读(1028)  评论(0)    收藏  举报