I am trying to call string.Format
using Tree
It took me a bit of work since my supply params Expression[] _ParameterExpressions
does not match signature of string.Format
which accept object[]
it seems it won't apply implicit conversion.
My current solution is to convert my supplied parameter into object[]
using
NewArrayExpression _NewArray = Expression.NewArrayInit(typeof(object), _ParameterExpressions.Select(ep => Expression.Convert(ep, typeof(object))));
and setup my proxy function to pass parameters to string.Format
(I need this or else it would say it could not find matched signature)
static string ReplaceParameters(string format, params object[] obj)
{
return string.Format(format, obj);
}
static IEnumerable<Expression> ReplaceStringExpression(Expression exp)
{
yield return exp;
yield return _NewArray;
}
And finally my call
ConstantExpression ce = Expression.Constant(orginalString, typeof(string));
MethodCallExpression me = Expression.Call(typeof(RuleParser), "ReplaceParameters", null,
ReplaceStringExpression(ce).ToArray());
The expression works but I don't really like the idea of creating new array which includes extra boxing process. I think it was overdone on such simple function call.
How can I improve this string.Format
call?
==========
Edit
Have some progress on my study. I can now ditch ReplaceParameters
but still don't like to create array of object _NewArray
MethodCallExpression me = Expression.Call(
typeof(string).GetMethod("Format", new Type[2] { typeof(string), typeof(object[]) }),
ReplaceStringExpression(ce).ToArray());