/// <summary> /// 將一個類型對象數據賦值到另一個類型對象(名字相同的情況) /// </summary> /// <typeparam name="T">目標類型</typeparam> /// <param name="entity">目標類型對象</param> /// <param name="dto">源對象</param> /// <returns></returns> public static object EntityDataEntity<T>(T entity, object dto) where T:class,new() { //if (dto == null || entity == null){return entity;} //System.Reflection.PropertyInfo[] entityProperties = entity.GetType().GetProperties(System.Reflection.BindingFlags.Public); //System.Reflection.PropertyInfo[] dtoProperties = dto.GetType().GetProperties(System.Reflection.BindingFlags.Public); System.Reflection.PropertyInfo[] entityProperties = entity.GetType().GetProperties(); System.Reflection.PropertyInfo[] dtoProperties = dto.GetType().GetProperties(); if (entityProperties.Length<=0){return entity;} if (dtoProperties.Length <= 0){return entity;} foreach (System.Reflection.PropertyInfo item in entityProperties) { foreach (var dtoItem in dtoProperties) { if (item.Name == dtoItem.Name) { if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { object value = dtoItem.GetValue(dto, null); if (value != null) item.SetValue(entity, value, null); break; } else { object value = item.GetValue(entity, null); object dtoValue=dtoItem.GetValue(dto, null); value = EntityDataEntity(value, dtoValue); if (value != null) item.SetValue(entity, value, null); break; } } } } return entity; }