ASP.Net MVC中有一个DisplayNameFor(x=>x.Title)帮助器。我想实现类似的行为。我想有一个方法,该方法可以接受基于User类(u=>u.Birthdate或u => u.Name)的表达式,一个操作数(Greater,Less,Equal)和类似DateTime.Now的值并返回一个表达式我知道我将不得不手动构建片段的结果表达式。我无法解决的是传递和处理属性表达式。编辑:我想调用一个像u=>u.Birthdate > DateTime.Now要么GetFilterPredicate(u=>u.Birthdate,FilterOps.GreaterThan,DateTime.Parse("01.01.2013")更新:我已经创建了一个仓库来解决这个问题,并收集了一个属性过滤器https://github.com/Alexander-Taran/Lambda-Magic-Filters (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 这是否满足您的需求?[TestClass]public class UnitTest1{ public Expression<Predicate<T>> GetFilterPredicate<T, R>(Expression<Func<T, R>> selector, FilterOps operand, R value) { var parameter = selector.Parameters[0]; var left = selector.Body; var right = Expression.Constant(value); var binaryExpression = Expression.MakeBinary(operand.ToExpressionType(), left, right); return Expression.Lambda<Predicate<T>>(binaryExpression, parameter); } [TestMethod] public void TestMethod1() { var p1 = this.GetFilterPredicate((User u) => u.Birthday.TimeOfDay.Hours, FilterOps.LessThan, 12); var p2 = this.GetFilterPredicate((User u) => u.Size, FilterOps.Equal, 180); var user = new User() { Birthday = new DateTime(2000, 1, 1), Size = 180 }; Assert.IsTrue(p1.Compile()(user)); Assert.IsTrue(p2.Compile()(user)); }}public enum FilterOps{ GreaterThan, LessThan, Equal}public static class MyExtensions{ public static ExpressionType ToExpressionType(this FilterOps operand) { switch (operand) { case FilterOps.GreaterThan: return ExpressionType.GreaterThan; case FilterOps.LessThan: return ExpressionType.LessThan; case FilterOps.Equal: return ExpressionType.Equal; default: throw new NotSupportedException(); } }}public class User { public DateTime Birthday { get; set; } public int Size { get; set; } } (adsbygoogle = window.adsbygoogle || []).push({}); 08-16 20:29