網站首頁 編程語言 正文
需求背景:對象復制性能優化;同時,在對象復制時,應跳過引用類型的null值復制,值類型支持值類型向可空類型的復制
using Common; using System; class Program { static void Main(string[] args) { TestClassA classA = new TestClassA() { PropA = new TestClass() { Name = "cs1" }, PropB = "c1", PropC = 1 }; TestClassA classB = new TestClassA() { PropA = new TestClass() { Name = "cs2" }, PropB = "c2", PropC = 2 }; FastCopy.Copy(classA, classB, false); Console.WriteLine(classB.PropA?.Name + ":" + classB.PropB + ":" + classB.PropC); TestClassA classC = new TestClassA() { PropA = new TestClass() { Name = "cs1" } }; TestClassA classD = new TestClassA() { PropA = new TestClass() { Name = "cs2" }, PropB = "c2", PropC = 2 }; FastCopy.Copy(classC, classD, false); Console.WriteLine(classD.PropA?.Name + ":" + classD.PropB + ":" + classD.PropC); } } public class TestClassA { public TestClass PropA { get; set; } public string PropB { get; set; } public int? PropC { get; set; } } public class TestClass { public string Name { get; set; } }
輸出:
百萬次調用耗時:270-300ms
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using static System.Linq.Expressions.Expression; namespace Common { public static class FastCopy { static ConcurrentDictionary<string, object> copiers = new ConcurrentDictionary<string, object>(); /// <summary> /// 復制兩個對象同名屬性值 /// </summary> /// <typeparam name="S"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="source">源對象</param> /// <param name="target">目標對象</param> /// <param name="copyNull">源對象屬性值為null時,是否將值復制給目標對象</param> public static void Copy<S, T>(S source, T target, bool copyNull = true) { string name = string.Format("{0}_{1}_{2}", typeof(S), typeof(T), copyNull); object targetCopier; if (!copiers.TryGetValue(name, out targetCopier)) { Action<S, T> copier = CreateCopier<S, T>(copyNull); copiers.TryAdd(name, copier); targetCopier = copier; } Action<S, T> action = (Action<S, T>)targetCopier; action(source, target); } /// <summary> /// 為指定的兩種類型編譯生成屬性復制委托 /// </summary> /// <typeparam name="S"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="copyNull">源對象屬性值為null時,是否將值復制給目標對象</param> /// <returns></returns> private static Action<S, T> CreateCopier<S, T>(bool copyNull) { ParameterExpression source = Parameter(typeof(S)); ParameterExpression target = Parameter(typeof(T)); var sourceProps = typeof(S).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanRead).ToList(); var targetProps = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanWrite).ToList(); // 查找可進行賦值的屬性 var copyProps = targetProps.Where(tProp => sourceProps.Where(sProp => sProp.Name == tProp.Name// 名稱一致 且 && ( sProp.PropertyType == tProp.PropertyType// 屬性類型一致 或 || sProp.PropertyType.IsAssignableFrom(tProp.PropertyType) // 源屬性類型 為 目標屬性類型 的 子類;eg:object target = string source; 或 || (tProp.PropertyType.IsValueType && sProp.PropertyType.IsValueType && // 屬性為值類型且基礎類型一致,但目標屬性為可空類型 eg:int? num = int num; ((tProp.PropertyType.GenericTypeArguments.Length > 0 ? tProp.PropertyType.GenericTypeArguments[0] : tProp.PropertyType) == sProp.PropertyType)) )).Count() > 0); List<Expression> expressionList = new List<Expression>(); foreach (var prop in copyProps) { if (prop.PropertyType.IsValueType)// 屬性為值類型 { PropertyInfo sProp = typeof(S).GetProperty(prop.Name); PropertyInfo tProp = typeof(T).GetProperty(prop.Name); if (sProp.PropertyType == tProp.PropertyType)// 屬性類型一致 eg:int num = int num; 或 int? num = int? num; { var assign = Assign(Property(target, prop.Name), Property(source, prop.Name)); expressionList.Add(assign); } else if (sProp.PropertyType.GenericTypeArguments.Length <= 0 && tProp.PropertyType.GenericTypeArguments.Length > 0)// 屬性類型不一致且目標屬性類型為可空類型 eg:int? num = int num; { var convert = Convert(Expression.Property(source, prop.Name), tProp.PropertyType); var cvAssign = Assign(Expression.Property(target, prop.Name), convert); expressionList.Add(cvAssign); } } else// 屬性為引用類型 { var assign = Assign(Property(target, prop.Name), Property(source, prop.Name));// 編譯生成屬性賦值語句 target.{PropertyName} = source.{PropertyName}; var sourcePropIsNull = Equal(Constant(null, prop.PropertyType), Property(source, prop.Name));// 判斷源屬性值是否為Null;編譯生成 source.{PropertyName} == null var setNull = IsTrue(Constant(copyNull));// 判斷是否復制Null值 編譯生成 copyNull == True var setNullTest = IfThen(setNull, assign); var condition = IfThenElse(sourcePropIsNull, setNullTest, assign); /** * 編譯生成 * if(source.{PropertyName} == null) * { * if(setNull) * { * target.{PropertyName} = source.{PropertyName}; * } * } * else * { * target.{PropertyName} = source.{PropertyName}; * } */ expressionList.Add(condition); } } var block = Block(expressionList.ToArray()); Expression<Action<S, T>> lambda = Lambda<Action<S, T>>(block, source, target); return lambda.Compile(); } } }
如果完整復制,去掉邏輯判斷,同時可通過泛型類,不在使用字典,性能還可以提升。
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Common { public static class FastCopy<S, T> { static Action<S, T> action = CreateCopier(); /// <summary> /// 復制兩個對象同名屬性值 /// </summary> /// <typeparam name="S"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="source">源對象</param> /// <param name="target">目標對象</param> /// <param name="copyNull">源對象屬性值為null時,是否將值復制給目標對象</param> public static void Copy(S source, T target, bool copyNull = true) { action(source, target); } /// <summary> /// 為指定的兩種類型編譯生成屬性復制委托 /// </summary> /// <typeparam name="S"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="copyNull">源對象屬性值為null時,是否將值復制給目標對象</param> /// <returns></returns> private static Action<S, T> CreateCopier() { ParameterExpression source = Expression.Parameter(typeof(S)); ParameterExpression target = Expression.Parameter(typeof(T)); var sourceProps = typeof(S).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanRead).ToList(); var targetProps = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanWrite).ToList(); // 查找可進行賦值的屬性 var copyProps = targetProps.Where(tProp => sourceProps.Where(sProp => sProp.Name == tProp.Name// 名稱一致 且 && ( sProp.PropertyType == tProp.PropertyType// 屬性類型一致 )).Count() > 0); var block = Expression.Block(from p in copyProps select Expression.Assign(Expression.Property(target, p.Name), Expression.Property(source, p.Name))); Expression<Action<S, T>> lambda = Expression.Lambda<Action<S, T>>(block, source, target); return lambda.Compile(); } } }
百萬次耗時:100ms左右
原文鏈接:https://www.cnblogs.com/mq0036/p/15762333.html
相關推薦
- 2022-08-02 C#中DateTime函數的詳細用法_C#教程
- 2023-01-03 python案例中Flask全局配置示例詳解_python
- 2022-06-23 Python在畫圖時使用特殊符號的方法總結_python
- 2022-03-30 C語言關鍵字之auto?register詳解_C 語言
- 2022-02-13 如何將pytorch模型部署到安卓
- 2022-05-11 spring cloud alibaba nacos搭建最小可運行微服務
- 2022-06-01 c++深入淺出講解堆排序和堆_C 語言
- 2023-07-04 ES聚合查詢+條件搜索的實現
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支