2012-09-02 32 views
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()); 

回答

2
  1. 当ExpressionTree是由编译器创建的 - 它包含所有必需的隐式转换,使选定的方法超负荷工作

    Expression<Func<string>> compilerFactoredExpressionTree =() => string.Format("{0} and {1} and {2} and {3}", 1, "text", true, 2); 
    // test 
    // "1 and text and True and 2" 
    string s = compilerFactoredExpressionTree.Compile()(); 
    // ArrayInit(Convert(1), Convert("text", Convert(2))) 
    Expression methodArgs = ((MethodCallExpression)compilerFactoredExpressionTree.Body).Arguments[1]; 
    
  2. 如果您手动构建ExpressionTree - 你需要作为自己的编译器 - 通过手插入转换或最初与所需类型

    声明值
    var parameters = new Expression[] 
    { 
        Expression.Constant(1, typeof(object)), 
        Expression.Constant("text", typeof(object)), 
        Expression.Constant(true, typeof(object)), 
        Expression.Constant(2, typeof(object)), 
    }; 
    
    var mi = new Func<string, object[], string>(string.Format).Method; 
    
    var callStringFormat = Expression.Call(mi, Expression.Constant("{0} and {1} and {2} and {3}"), Expression.NewArrayInit(typeof(object), parameters)); 
    
    // "1 and text and True and 2" 
    var lambda = Expression.Lambda<Func<string>>(callStringFormat); 
    var r = lambda.Compile()(); 
    
+0

我明白了。这就是重点。谢谢! – ipoppo