Created
April 11, 2011 20:28
-
-
Save Antaris/914257 to your computer and use it in GitHub Desktop.
Extends the System.Linq.Dynamic.ExpressionParser sample to build a generic expression parser.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class FunctionFactory | |
{ | |
private static Delegate CreateInternal(Type[] argumentTypes, Type returnType, string expression, string[] argumentNames = null) | |
{ | |
if (argumentNames != null) | |
{ | |
if (argumentTypes.Length != argumentNames.Length) | |
throw new ArgumentException("The number of argument names does not equal the number of argument types."); | |
} | |
var @params = argumentTypes.Select( | |
(t, i) => Expression.Parameter(t, argumentNames[i])).ToArray(); | |
ExpressionParser parser = new ExpressionParser(@params, expression, null); | |
var @delegate = Expression.Lambda(parser.Parse(returnType), @params).Compile(); | |
return @delegate; | |
} | |
public static Func<TReturn> Create<TReturn>(string expression, string[] argumentNames = null) | |
{ | |
return (Func<TReturn>)CreateInternal(new Type[0], typeof(TReturn), expression, argumentNames); | |
} | |
public static Func<A, TReturn> Create<A, TReturn>(string expression, string[] argumentNames = null) | |
{ | |
return (Func<A, TReturn>)CreateInternal(new[] { typeof(A) }, typeof(TReturn), expression, argumentNames); | |
} | |
public static Func<A, B, TReturn> Create<A, B, TReturn>(string expression, string[] argumentNames = null) | |
{ | |
return (Func<A, B, TReturn>)CreateInternal(new[] { typeof(A), typeof(B) }, typeof(TReturn), expression, argumentNames); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment