相同属性类之间的转换

web开发常会遇到model转换的问题

比如一个Person类

数据库的表示 是Person

展现层是PersonViewModel

作为传参是PersonRequest

说道这里大家应该想到AutoMappler了。

当然自己也可以简单的实现,只要通过反射加上泛型就可以简单实现了

代码如下:

public static TTarget ConvertModel<TSource, TTarget>(TSource source) where TTarget : class
        {
            if (source == null)
            {
                return null;
            }

            TTarget obj = Activator.CreateInstance(typeof(TTarget)) as TTarget;//创建目标对象的实例
            var sourceProperties = typeof(TSource).GetProperties();

            foreach (var item in typeof(TTarget).GetProperties())
            {
                if (!item.CanWrite) { continue; }
                var sourceProp = sourceProperties.FirstOrDefault(o => o.Name == item.Name);//用linq代理for循环
                //如果没有该属性继续
                if (sourceProp == null || !sourceProp.CanRead || sourceProp.PropertyType != item.PropertyType)
                {
                    continue;
                }
                item.SetValue(obj, sourceProp.GetValue(source));//将源的值赋给目标
            }
            return obj;
        }

猜你喜欢

转载自www.cnblogs.com/MarkSun3/p/9481282.html