不同对象相同字段名间映射

    /// <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;
        }
    }

  

posted @ 2023-10-19 16:17  Ciel Water  阅读(10)  评论(0编辑  收藏  举报