排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

两个对象相同属性赋值,可以减少一个一个属性点出来赋值,用一点反射即可搞定
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)); } } }
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价