一个类反射给另一个类并且:获取数组长度以及集合的长度和类型,判断是否为数组和集合是否为空,以及其他类型是否为空
我是直接综合到了我的AutoMapperHelper 类里面,跟我的映射放在一起了,不要介意使用方法的名字
我这里使用的两个类反射,由 S 转给 T
目前使用的都是 泛型集合 里面的集合数组,所以判断泛型就判断了集合
public static T MapperTo<T, S>(T t,S s) { try { var Types = s.GetType(); var Typed = t.GetType(); foreach (PropertyInfo sp in Types.GetProperties()) { foreach (PropertyInfo dp in Typed.GetProperties()) { if (dp.Name == sp.Name && sp.Name!="Id") { if (sp.PropertyType.FullName.Contains("Generic")|| sp.PropertyType.IsArray) { if (((IEnumerable<object>)sp.GetValue(s, null)).Count() != 0) { dp.SetValue(t, sp.GetValue(s, null), null); } } else { if (sp.GetValue(s, null) != null) { dp.SetValue(t, sp.GetValue(s, null), null); } } } } } } catch (Exception ex) { throw ex; } return t; }
上面综合了常见的 一些类型,由S表反射给T表,如果S的某个值为空则不给T赋值,集合等类型长度为0也不给T赋值
使用方法
var result= MapperTo<A, B>(A,B)//这个是把B类不为空的数据赋值给A ,为空则保持A类数据的完整 var result= MapperTo<B, A>(B,A) //反之 把A数据插入到B中
如果还有别的需求给几个样例:
这个是取是否为集合,不过经过我测试某种不知为啥会有sring类型漏进来,不过可能是我数据问题
var ts = sp.PropertyType.FullName; 替换为|| v var ts = sp.PropertyType. GetInterface(typeof(IEnumerable<>).FullName);//是否是集合 结果:ts = true 或者 fase typeof(List<>) typeof(string) typeof(int) 可以替换类型
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号