LambdaBuilder.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq.Expressions;
  5. using System.Reflection.Emit;
  6. using System.Runtime.CompilerServices;
  7. using JetBrains.Annotations;
  8. namespace IwbZero.ToolCommon.Lambda
  9. {
  10. // Codes below are taken from https://github.com/scottksmith95/LINQKit project.
  11. /// <summary> 运算符 </summary>
  12. public enum PredicateOperator
  13. {
  14. /// <summary> The "Or" </summary>
  15. Or,
  16. /// <summary> The "And" </summary>
  17. And
  18. }
  19. /// <summary>
  20. /// See http://www.albahari.com/expressions for information and examples.
  21. /// </summary>
  22. public static class LambdaBuilder
  23. {
  24. private class RebindParameterVisitor : ExpressionVisitor
  25. {
  26. private readonly ParameterExpression _oldParameter;
  27. private readonly ParameterExpression _newParameter;
  28. public RebindParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
  29. {
  30. _oldParameter = oldParameter;
  31. _newParameter = newParameter;
  32. }
  33. protected override Expression VisitParameter(ParameterExpression node)
  34. {
  35. if (node == _oldParameter)
  36. {
  37. return _newParameter;
  38. }
  39. return base.VisitParameter(node);
  40. }
  41. }
  42. /// <summary> 启动表达式 </summary>
  43. public static ExpressionStarter<T> New<T>(Expression<Func<T, bool>> expr = null) { return new ExpressionStarter<T>(expr); }
  44. /// <summary> 使用存根表达式true或false创建表达式,以便在表达式尚未启动时使用。 </summary>
  45. public static ExpressionStarter<T> New<T>(bool defaultExpression) { return new ExpressionStarter<T>(defaultExpression); }
  46. /// <summary> Always true </summary>
  47. [Obsolete("Use PredicateBuilder.New() instead.")]
  48. public static Expression<Func<T, bool>> True<T>() { return new ExpressionStarter<T>(true); }
  49. /// <summary> Always false </summary>
  50. [Obsolete("Use PredicateBuilder.New() instead.")]
  51. public static Expression<Func<T, bool>> False<T>() { return new ExpressionStarter<T>(false); }
  52. /// <summary> OR </summary>
  53. public static Expression<Func<T, bool>> Or<T>([NotNull] this Expression<Func<T, bool>> expr1, [NotNull] Expression<Func<T, bool>> expr2)
  54. {
  55. var expr2Body = new RebindParameterVisitor(expr2.Parameters[0], expr1.Parameters[0]).Visit(expr2.Body);
  56. return Expression.Lambda<Func<T, bool>>(Expression.OrElse(expr1.Body, expr2Body), expr1.Parameters);
  57. }
  58. /// <summary> AND </summary>
  59. public static Expression<Func<T, bool>> And<T>([NotNull] this Expression<Func<T, bool>> expr1, [NotNull] Expression<Func<T, bool>> expr2)
  60. {
  61. var expr2Body = new RebindParameterVisitor(expr2.Parameters[0], expr1.Parameters[0]).Visit(expr2.Body);
  62. return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, expr2Body), expr1.Parameters);
  63. }
  64. /// <summary>
  65. ///用指定的运算符扩展表达式。
  66. /// </summary>
  67. /// <typeparam name="T">The type</typeparam>
  68. /// <param name="first">The source Predicate.</param>
  69. /// <param name="second">The second Predicate.</param>
  70. /// <param name="operator">The Operator (can be "And" or "Or").</param>
  71. /// <returns>Expression{Func{T, bool}}</returns>
  72. public static Expression<Func<T, bool>> Extend<T>([NotNull] this Expression<Func<T, bool>> first, [NotNull] Expression<Func<T, bool>> second, PredicateOperator @operator = PredicateOperator.Or)
  73. {
  74. return @operator == PredicateOperator.Or ? first.Or(second) : first.And(second);
  75. }
  76. /// <summary>
  77. /// 用指定的运算符扩展表达式。
  78. /// </summary>
  79. /// <typeparam name="T">The type</typeparam>
  80. /// <param name="first">The source Predicate.</param>
  81. /// <param name="second">The second Predicate.</param>
  82. /// <param name="operator">The Operator (can be "And" or "Or").</param>
  83. /// <returns>Expression{Func{T, bool}}</returns>
  84. public static Expression<Func<T, bool>> Extend<T>([NotNull] this ExpressionStarter<T> first, [NotNull] Expression<Func<T, bool>> second, PredicateOperator @operator = PredicateOperator.Or)
  85. {
  86. return @operator == PredicateOperator.Or ? first.Or(second) : first.And(second);
  87. }
  88. }
  89. /// <summary>
  90. /// ExpressionStarter{T} 它消除了默认的1=0或1=1存根表达式
  91. /// </summary>
  92. /// <typeparam name="T">The type</typeparam>
  93. public class ExpressionStarter<T>
  94. {
  95. internal ExpressionStarter() : this(false)
  96. {
  97. }
  98. internal ExpressionStarter(bool defaultExpression)
  99. {
  100. if (defaultExpression)
  101. DefaultExpression = f => true;
  102. else
  103. DefaultExpression = f => false;
  104. }
  105. internal ExpressionStarter(Expression<Func<T, bool>> exp) : this(false)
  106. {
  107. _predicate = exp;
  108. }
  109. /// <summary>实际谓词。只能通过调用Start来设置。</summary>
  110. private Expression<Func<T, bool>> Predicate => (IsStarted || !UseDefaultExpression) ? _predicate : DefaultExpression;
  111. private Expression<Func<T, bool>> _predicate;
  112. /// <summary>确定谓词是否已启动。 </summary>
  113. public bool IsStarted => _predicate != null;
  114. /// <summary> 仅当表达式为空时使用的默认表达式 </summary>
  115. public bool UseDefaultExpression => DefaultExpression != null;
  116. /// <summary>默认表达式</summary>
  117. public Expression<Func<T, bool>> DefaultExpression { get; set; }
  118. /// <summary>设置表达式谓词</summary>
  119. /// <param name="exp">The first expression</param>
  120. public Expression<Func<T, bool>> Start(Expression<Func<T, bool>> exp)
  121. {
  122. if (IsStarted)
  123. throw new Exception("Predicate cannot be started again.");
  124. return _predicate = exp;
  125. }
  126. /// <summary>Or</summary>
  127. public Expression<Func<T, bool>> Or([NotNull] Expression<Func<T, bool>> expr2)
  128. {
  129. return (IsStarted) ? _predicate = Predicate.Or(expr2) : Start(expr2);
  130. }
  131. /// <summary>And</summary>
  132. public Expression<Func<T, bool>> And([NotNull] Expression<Func<T, bool>> expr2)
  133. {
  134. return (IsStarted) ? _predicate = Predicate.And(expr2) : Start(expr2);
  135. }
  136. /// <summary> Show predicate string </summary>
  137. public override string ToString()
  138. {
  139. return Predicate?.ToString() ?? throw new InvalidOperationException();
  140. }
  141. #region Implicit Operators
  142. /// <summary>
  143. /// Allows this object to be implicitely converted to an Expression{Func{T, bool}}.
  144. /// </summary>
  145. /// <param name="right"></param>
  146. public static implicit operator Expression<Func<T, bool>>(ExpressionStarter<T> right)
  147. {
  148. return right == null ? null : right.Predicate;
  149. }
  150. /// <summary>
  151. /// Allows this object to be implicitely converted to an Expression{Func{T, bool}}.
  152. /// </summary>
  153. /// <param name="right"></param>
  154. public static implicit operator Func<T, bool>(ExpressionStarter<T> right)
  155. {
  156. return right == null ? null : (right.IsStarted || right.UseDefaultExpression) ? right.Predicate.Compile() : null;
  157. }
  158. /// <summary>
  159. /// Allows this object to be implicitely converted to an Expression{Func{T, bool}}.
  160. /// </summary>
  161. /// <param name="right"></param>
  162. public static implicit operator ExpressionStarter<T>(Expression<Func<T, bool>> right)
  163. {
  164. return right == null ? null : new ExpressionStarter<T>(right);
  165. }
  166. #endregion Implicit Operators
  167. #region Implement Expression<TDelagate> methods and properties
  168. #if !(NET35)
  169. /// <summary></summary>
  170. public Func<T, bool> Compile() { return Predicate.Compile(); }
  171. #endif
  172. #if !(NET35 || WINDOWS_APP || NETSTANDARD || PORTABLE || PORTABLE40 || UAP)
  173. /// <summary></summary>
  174. public Func<T, bool> Compile(DebugInfoGenerator debugInfoGenerator) { return Predicate.Compile(debugInfoGenerator); }
  175. /// <summary></summary>
  176. public Expression<Func<T, bool>> Update(Expression body, IEnumerable<ParameterExpression> parameters) { return Predicate.Update(body, parameters); }
  177. #endif
  178. #endregion Implement Expression<TDelagate> methods and properties
  179. #region Implement LamdaExpression methods and properties
  180. /// <summary></summary>
  181. public Expression Body => Predicate.Body;
  182. /// <summary></summary>
  183. public ExpressionType NodeType => Predicate.NodeType;
  184. /// <summary></summary>
  185. public ReadOnlyCollection<ParameterExpression> Parameters => Predicate.Parameters;
  186. /// <summary></summary>
  187. public Type Type => Predicate.Type;
  188. #if !(NET35)
  189. /// <summary></summary>
  190. public string Name => Predicate.Name;
  191. /// <summary></summary>
  192. public Type ReturnType => Predicate.ReturnType;
  193. /// <summary></summary>
  194. public bool TailCall => Predicate.TailCall;
  195. #endif
  196. #if !(NET35 || WINDOWS_APP || NETSTANDARD || PORTABLE || PORTABLE40 || UAP)
  197. /// <summary></summary>
  198. public void CompileToMethod(MethodBuilder method) { Predicate.CompileToMethod(method); }
  199. /// <summary></summary>
  200. public void CompileToMethod(MethodBuilder method, DebugInfoGenerator debugInfoGenerator) { Predicate.CompileToMethod(method, debugInfoGenerator); }
  201. #endif
  202. #endregion Implement LamdaExpression methods and properties
  203. #region Implement Expression methods and properties
  204. #if !(NET35)
  205. /// <summary></summary>
  206. public virtual bool CanReduce => Predicate.CanReduce;
  207. #endif
  208. #endregion Implement Expression methods and properties
  209. }
  210. }