Skip to content

Instantly share code, notes, and snippets.

@Antaris
Created April 11, 2011 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Antaris/914257 to your computer and use it in GitHub Desktop.
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.
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