不同对象相同字段名间映射
/// <summary> /// 对象映射扩展方法 /// </summary> public static class MappingUtil { /// <summary> /// 对象映射 /// </summary> /// <typeparam name="TTarget">目标类</typeparam> /// <typeparam name="TSource">源类</typeparam> /// <param name="targetObject">目标对象</param> /// <param name="sourceObject">源对象</param> public static TTarget ObjectMapping<TTarget, TSource>(this TTarget targetObject, TSource sourceObject) { object value; var targetType = targetObject?.GetType(); var sourceType = sourceObject?.GetType(); foreach (var item in sourceType.GetProperties()) { try { value = sourceType.GetProperty(item.Name)?.GetValue(sourceObject); if (value == null) { continue; } targetType.GetProperty(item.Name)?.SetValue(targetObject, value); } catch (Exception) { continue; } } return targetObject; } }