diff --git a/src/DynamicExpresso.Core/Lambda.cs b/src/DynamicExpresso.Core/Lambda.cs index 4b3e3fef..e89edbb8 100644 --- a/src/DynamicExpresso.Core/Lambda.cs +++ b/src/DynamicExpresso.Core/Lambda.cs @@ -14,28 +14,22 @@ public class Lambda { private readonly Expression _expression; private readonly ParserArguments _parserArguments; - - private readonly Delegate _delegate; + private readonly Lazy _delegate; internal Lambda(Expression expression, ParserArguments parserArguments) { - if (expression == null) - throw new ArgumentNullException("expression"); - if (parserArguments == null) - throw new ArgumentNullException("parserArguments"); - - _expression = expression; - _parserArguments = parserArguments; + _expression = expression ?? throw new ArgumentNullException(nameof(expression)); + _parserArguments = parserArguments ?? throw new ArgumentNullException(nameof(parserArguments)); - // Note: I always compile the generic lambda. Maybe in the future this can be a setting because if I generate a typed delegate this compilation is not required. - var lambdaExpression = Expression.Lambda(_expression, _parserArguments.UsedParameters.Select(p => p.Expression).ToArray()); - _delegate = lambdaExpression.Compile(); + // Note: I always lazy compile the generic lambda. Maybe in the future this can be a setting because if I generate a typed delegate this compilation is not required. + _delegate = new Lazy(() => + Expression.Lambda(_expression, _parserArguments.UsedParameters.Select(p => p.Expression).ToArray()).Compile()); } public Expression Expression { get { return _expression; } } public bool CaseInsensitive { get { return _parserArguments.Settings.CaseInsensitive; } } public string ExpressionText { get { return _parserArguments.ExpressionText; } } - public Type ReturnType { get { return _delegate.Method.ReturnType; } } + public Type ReturnType { get { return Expression.Type; } } /// /// Gets the parameters actually used in the expression parsed. @@ -112,7 +106,7 @@ private object InvokeWithUsedParameters(object[] orderedArgs) { try { - return _delegate.DynamicInvoke(orderedArgs); + return _delegate.Value.DynamicInvoke(orderedArgs); } catch (TargetInvocationException exc) { diff --git a/src/DynamicExpresso.Core/Parameter.cs b/src/DynamicExpresso.Core/Parameter.cs index 03b0c4e6..cf491858 100644 --- a/src/DynamicExpresso.Core/Parameter.cs +++ b/src/DynamicExpresso.Core/Parameter.cs @@ -38,6 +38,11 @@ public Parameter(string name, Type type, object value = null) Expression = System.Linq.Expressions.Expression.Parameter(type, name); } + public static Parameter Create(string name, T value) + { + return new Parameter(name, typeof(T), value); + } + public string Name { get; private set; } public Type Type { get; private set; } public object Value { get; private set; }