上接《只要十步 , 你就可以应用表达式树来优化动态调用(一)》
第六步 , 将静态方法换为表达式ValidateStringRequired 和 ValidateStringMinLength 两个静态方法的内部实际上只包含一个判断三目表达式 , 而且在 C# 中 , 可以将 Lambda 方法赋值个一个表达式 。
因此 , 我们可以直接将 ValidateStringRequired 和 ValidateStringMinLength 改换为表达式 , 这样就不需要反射来获取静态方法再去构建表达式了 。
using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Diagnostics;using System.Linq;using System.Linq.Expressions;using System.Reflection;using FluentAssertions;using NUnit.Framework;// ReSharper disable InvalidXmlDocCommentnamespace Newbe.ExpressionsTests{////// Static Method to Expression///public class X03PropertyValidationTest06{private const int Count = 10_000;private static Func _func;[SetUp]public void Init(){try{var finalExpression = CreateCore();_func = finalExpression.Compile();Expression> CreateCore(){// exp for inputvar inputExp = Expression.Parameter(typeof(CreateClaptrapInput), "input");// exp for outputvar resultExp = Expression.Variable(typeof(ValidateResult), "result");// exp for return statementvar returnLabel = Expression.Label(typeof(ValidateResult));var innerExps = new List {CreateDefaultResult()};var stringProps = typeof(CreateClaptrapInput).GetProperties().Where(x => x.PropertyType == typeof(string));foreach (var propertyInfo in stringProps){if (propertyInfo.GetCustomAttribute() != null){innerExps.Add(CreateValidateStringRequiredExpression(propertyInfo));}var minlengthAttribute = propertyInfo.GetCustomAttribute();if (minlengthAttribute != null){innerExps.Add(CreateValidateStringMinLengthExpression(propertyInfo, minlengthAttribute.Length));}}innerExps.Add(Expression.Label(returnLabel, resultExp));// build whole blockvar body = Expression.Block(new[] {resultExp},innerExps);// build lambda from bodyvar final = Expression.Lambda>(body,inputExp);return final;Expression CreateDefaultResult(){var okMethod = typeof(ValidateResult).GetMethod(nameof(ValidateResult.Ok));Debug.Assert(okMethod != null, nameof(okMethod) + " != null");var methodCallExpression = Expression.Call(okMethod);var re = Expression.Assign(resultExp, methodCallExpression);/*** final as:* result = ValidateResult.Ok()*/return re;}Expression CreateValidateStringRequiredExpression(PropertyInfo propertyInfo){var isOkProperty = typeof(ValidateResult).GetProperty(nameof(ValidateResult.IsOk));Debug.Assert(isOkProperty != null, nameof(isOkProperty) + " != null");var namePropExp = Expression.Property(inputExp, propertyInfo);var nameNameExp = Expression.Constant(propertyInfo.Name);var requiredMethodExp = Expression.Invoke(ValidateStringRequiredExp, nameNameExp, namePropExp);var assignExp = Expression.Assign(resultExp, requiredMethodExp);var resultIsOkPropertyExp = Expression.Property(resultExp, isOkProperty);var conditionExp = Expression.IsFalse(resultIsOkPropertyExp);var ifThenExp =Expression.IfThen(conditionExp,Expression.Return(returnLabel, resultExp));var re = Expression.Block(new[] {resultExp},assignExp,ifThenExp);return re;}Expression CreateValidateStringMinLengthExpression(PropertyInfo propertyInfo,int minlengthAttributeLength){var isOkProperty = typeof(ValidateResult).GetProperty(nameof(ValidateResult.IsOk));Debug.Assert(isOkProperty != null, nameof(isOkProperty) + " != null");var namePropExp = Expression.Property(inputExp, propertyInfo);var nameNameExp = Expression.Constant(propertyInfo.Name);var requiredMethodExp = Expression.Invoke(ValidateStringMinLengthExp,nameNameExp,namePropExp,Expression.Constant(minlengthAttributeLength));var assignExp = Expression.Assign(resultExp, requiredMethodExp);var resultIsOkPropertyExp = Expression.Property(resultExp, isOkProperty);var conditionExp = Expression.IsFalse(resultIsOkPropertyExp);var ifThenExp =Expression.IfThen(conditionExp,Expression.Return(returnLabel, resultExp));var re = Expression.Block(new[] {resultExp},assignExp,ifThenExp);return re;}}}catch (Exception e){Console.WriteLine(e);throw;}}[Test]public void Run(){// see code in demo repo}private static readonly Expression
推荐阅读
-
-
成龙 |息影38年的影后,只有成龙才能请她出山,仅出镜一分钟依然被认出
-
同比增长|佳电股份:前三季度净利预增37%-45%
-
美家美宿@【泰式柠檬凤爪】的做法+配方,爽口解馋零食,酸辣美味停不下来
-
-
陈楚生自曝家里曾卖拖鞋,得知张远家拖鞋需求大,感叹错失大客户
-
-
环球时报|1月乌克兰客机坠毁最新调查结果:第一枚导弹击中后乘客本还活着
-
-
穿越火线手游赛事|联盟“百花齐放”时代来临,双冠R.LGD只是开始
-
直播吧官方球员将在酒店集中住宿,德媒:拜仁明日恢复团队训练
-
青年|王者荣耀:李信世冠皮肤上线后,李信玩家集体后悔了!
-
崛起我的国|强国真正目标浮出水面,印军醒悟后为时已晚,班公湖果然是个幌子
-
|钓鱼时鱼竿卡住怎么办?蛮力容易弄断鱼竿,渔具店老板给涨知识
-
软件:品高软件冲刺科创板 募资金额近5成拟建总部大楼
-
『阿梁1994』无人可以幸免,中国粮食储备还够14亿人吃多,假如全球疫情大爆发
-
新华网|山西公布疾控机构核酸收费标准:60元每人次,自愿检测
-
银行|《心居》三大意外:冯晓琴有私生子,顾清俞吻懵展翔,冯茜茜暧昧顾昕
-
说说校园欺凌给你或者当时你认识的小朋友带来了怎么样的影响作为当事人或者其父母老师,应该怎样解决此事
-
适量|美味家常菜,鲜香下饭,好吃好做,全家老少都爱吃