修改了 CreateValidateNameRequiredExpression 和 CreateValidateNameMinLengthExpression , 因为静态方法的参数发生了变化 。 通过这样的改造 , 我们便可以将两个静态方法用于更多的属性验证 。 读者可以尝试增加一个 NickName 属性 。 并且进行相同的验证 。 第四步 , 支持多个属性验证接下来 , 我们通过将验证 CreateClaptrapInput 所有的 string 属性 。
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{////// Reflect Properties///public class X03PropertyValidationTest04{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");var minLengthPExp = Expression.Parameter(typeof(int), "minLength");// 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){innerExps.Add(CreateValidateStringRequiredExpression(propertyInfo));innerExps.Add(CreateValidateStringMinLengthExpression(propertyInfo));}innerExps.Add(Expression.Label(returnLabel, resultExp));// build whole blockvar body = Expression.Block(new[] {resultExp},innerExps);// build lambda from bodyvar final = Expression.Lambda>(body,inputExp,minLengthPExp);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 requireMethod = typeof(X03PropertyValidationTest04).GetMethod(nameof(ValidateStringRequired));var isOkProperty = typeof(ValidateResult).GetProperty(nameof(ValidateResult.IsOk));Debug.Assert(requireMethod != null, nameof(requireMethod) + " != null");Debug.Assert(isOkProperty != null, nameof(isOkProperty) + " != null");var namePropExp = Expression.Property(inputExp, propertyInfo);var nameNameExp = Expression.Constant(propertyInfo.Name);var requiredMethodExp = Expression.Call(requireMethod, 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){var minLengthMethod =typeof(X03PropertyValidationTest04).GetMethod(nameof(ValidateStringMinLength));var isOkProperty = typeof(ValidateResult).GetProperty(nameof(ValidateResult.IsOk));Debug.Assert(minLengthMethod != null, nameof(minLengthMethod) + " != null");Debug.Assert(isOkProperty != null, nameof(isOkProperty) + " != null");var namePropExp = Expression.Property(inputExp, propertyInfo);var nameNameExp = Expression.Constant(propertyInfo.Name);var requiredMethodExp = Expression.Call(minLengthMethod,nameNameExp,namePropExp,minLengthPExp);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}public static ValidateResult Validate(CreateClaptrapInput input){return _func.Invoke(input, 3);}public static ValidateResult ValidateStringRequired(string name, string value){return string.IsNullOrEmpty(value)? ValidateResult.Error($"missing {name}"): ValidateResult.Ok();}public static ValidateResult ValidateStringMinLength(string name, string value, int minLength){return value.Length
推荐阅读
-
新华社|外媒:拉美是受“信息疫情”影响最严重的地区
-
向往4:《向往4》张子枫全力冲刺高考!大清早起来复习,做笔记方式太真实了
-
美食承教事业上的女强人,家庭中的顶梁柱,聪明能干的四大生肖女
-
东方网|东方快评丨门票减免并非万能,练好内功才是正途
-
-
-
詹姆斯|利拉德再次力挺詹皇拿MVP:他将湖人从乐透区带到西部榜首
-
-
-
-
-
国务院国有资产监督管理委员会|国资委:央企上半年累计降低全社会运行成本超1200亿元
-
-
特斯拉|车顶维权女车主曝光庭审内容:特斯拉想要和解被其拒绝
-
过往年少|国产操作系统日趋完善,佳能、爱普生等品牌加速完成兼容测试
-
可爱的小冉|新的希望,迎接新的机遇,早安,新的一天
-
-
6G标准控制权争夺开始了?美、英等十国联合行动,网友:一盘散沙
-
第一线电竞|百万网友在线围观,无美颜无滤镜!孤影首次粉丝见面会强势来袭
-
楼市@美国印出来的楼市盛宴或将中道而止,高盛:1.2万亿美元将流入中国