故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

.net两个对象相同属性赋值

5262人阅读 2019/9/12 11:49 总访问:3918860 评论:0 收藏:1 手机
分类: .NET


两个对象相同属性赋值,可以减少一个一个属性点出来赋值,用一点反射即可搞定

    public class ModelTools
    {
        /// <summary>
        /// 模型赋值
        /// </summary>
        /// <param name="target">目标</param>
        /// <param name="source">数据源</param>
        public static void CopyModel(object target, object source)
        {
            Type targetType = target.GetType();
            Type sourceType = source.GetType();
            foreach (var mi in sourceType.GetProperties())
            {
                var des = targetType.GetProperty(mi.Name);
                if (des != null)
                {
                    des.SetValue(target, mi.GetValue(source));
                }
            }
        }
    }

用法:


如果不是每一个一样的都需要去拷贝,我们还可以设置忽略,直接传递需要忽略的属性名称即可,没有必要去搞一个什么特性配置反而麻烦了


泛型方法的写法:

        /// <summary>
        /// 模型赋值
        /// </summary>
        /// <param name="target">目标</param>
        /// <param name="source">数据源</param>
        public static void CopyModel<T, M>(T target, M source)
        {
            Type targetType = target.GetType();
            Type sourceType = source.GetType();
            foreach (var mi in sourceType.GetProperties())
            {
                var des = targetType.GetProperty(mi.Name);
                if (des != null)
                {
                    des.SetValue(target, mi.GetValue(source));
                }
            }
        }






欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价