如何使用BigCookieKit?
Install-Package BigCookieKit -Version 1.0.2021.224
高性能反射
为何性能高?
答:底层使用了Emit 整个功能机制是管理Emit指令集来实现高性能的反射
表达式树PK神器
首先引入命名空间
using BigCookieKit.Reflect;
表达式树代码
[Benchmark(Description = "ExpressionTree")]public void ExpressionTree(){ if (tree != null) { tree?.Invoke(); return; } var labelTarget = Expression.Label(typeof(Model)); var variable = Expression.Variable(typeof(Model)); var entity = Expression.Assign(variable, Expression.New(typeof(Model).GetConstructor(Type.EmptyTypes))); var field1 = typeof(Model).GetProperty("field1"); var field1Prop = Expression.Property(variable, field1); var assign1 = Expression.Assign(field1Prop, Expression.Constant("测试数据")); var field2 = typeof(Model).GetProperty("field2"); var field2Prop = Expression.Property(variable, field2); var assign2 = Expression.Assign(field2Prop, Expression.Constant(1000, typeof(int?))); var field3 = typeof(Model).GetProperty("field3"); var field3Prop = Expression.Property(variable, field3); var assign3 = Expression.Assign(field3Prop, Expression.Constant(13165M, typeof(decimal?))); var field4 = typeof(Model).GetProperty("field4"); var field4Prop = Expression.Property(variable, field4); var assign4 = Expression.Assign(field4Prop, Expression.Constant(DateTime.Now, typeof(DateTime?))); var block = Expression.Block( new ParameterExpression[] { variable }, entity, assign1, assign2, assign3, assign4, variable); var deleg = Expression.Lambda<Func<Model>>(block); tree = deleg.Compile(); tree?.Invoke();}反射神器代码
[Benchmark(Description = "EmitTool")]public void EmitTool(){ if (emit != null) { emit?.Invoke(); return; } emit = SmartBuilder.DynamicMethod<Func<Model>>(string.Empty, il => { var model = il.NewEntity<Model>(); model["field1"] = il.NewString("测试数据"); model["field2"] = il.NewInt32(1000).AsNullable(); model["field3"] = il.NewDecimal(13165M).AsNullable(); model["field4"] = il.NewDateTime().AsNullable(); model.Output(); il.Return(); }); emit?.Invoke();}接下来见证奇迹的时刻
不管从使用便捷度还是 最后的性能比较 都是神器更胜一筹