1
我试图用树完善的String.format CallExpression
调用string.Format
我花了一些工作,因为我的供应params Expression[] _ParameterExpressions
不匹配的string.Format
签署该接受object[]
现在看来,这将不适用的隐式转换。
我目前的解决方案是使用
NewArrayExpression _NewArray = Expression.NewArrayInit(typeof(object), _ParameterExpressions.Select(ep => Expression.Convert(ep, typeof(object))));
和设置我的代理功能将参数传递给string.Format
(我需要这个,否则它会说,它无法找到匹配的签名)
object[]
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;
}
最后我的电话
ConstantExpression ce = Expression.Constant(orginalString, typeof(string));
MethodCallExpression me = Expression.Call(typeof(RuleParser), "ReplaceParameters", null,
ReplaceStringExpression(ce).ToArray());
该表达式的作品,但我不太喜欢创建新的数组,其中包括额外的拳击过程的想法。我认为这种简单的函数调用过度了。
如何改进string.Format
调用?
==========
编辑
在我的研究中取得了一些进展。我现在能够摆脱ReplaceParameters
,但仍然不喜欢创建的对象的数组_NewArray
MethodCallExpression me = Expression.Call(
typeof(string).GetMethod("Format", new Type[2] { typeof(string), typeof(object[]) }),
ReplaceStringExpression(ce).ToArray());
我明白了。这就是重点。谢谢! – ipoppo