调用与表达(params对象[])[] [英] Calling (params object[]) with Expression[]

查看:181
本文介绍了调用与表达(params对象[])[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个Linq.Expression树调用的String.Format。这里有一个简单的例子:

I'm trying to call String.Format from with in a Linq.Expression tree. Here's a quick example:

    var format = Expression.Constant("({0}) {1}");
    var company = Expression.Property(input, membernames.First());
    var project = Expression.Property(input, membernames.Last());
    var args = new Expression[] {format, company, project};
    var invoke = Expression.Call(method,args);



然而,问题是,拥有的String.Format的签名:

The issue however is that String.Format has the signature of:

String.Format(string format, params object[] args)

和我想表达中的[]通过。

and I'm trying to pass in Expression[].

现在我可以通过创建一个数组,填充它的所有的麻烦我表达式的结果,但我真的希望得到的结果是,是这样的:

Now I could go through all the trouble of creating an array, populating it with the results of my expressions, but what I really want the result to be, is something like this:

String.Format("({0}) {1}", input.foo, input.bar)

怎么办我去通过LINQ表达式调用PARAMS功能?

How do I go about calling a params function via Linq Expressions?

推荐答案

什么 PARAMS 实际上做的是只指定 ParamArrayAttribute 该参数。 C#编译器理解这一点,并创建幕后的数组。

What params actually does is just to specify ParamArrayAttribute for that parameter. The C# compiler understands this, and creates the array behind the scenes.

如果你想表达的不明白这一点,所以你实际上必须自己创建数组,调用与 PARAMS的方法

Expressions don't understand this, so you actually have to create the array by yourself, if you want to call a method with params. This can be also seen by the fact that when you assign a lambda using params-method to an expression, the expression contains the array creation:

Expression<Func<string>> expression = () => string.Format("",1,2,3,4);
string expressionString = expression.ToString();



在这里, expressionString 将包含此字符串:

() => Format("", new [] {Convert(1), Convert(2), Convert(3), Convert(4)})

要创建创建一个数组的表达式,使用的 Expression.NewArrayInit()方法

To create an expression that creates an array, use the Expression.NewArrayInit() method.

话虽这么说,如果你只想要两个参数(或者一个或三个),有 的重载串.Format() ,你可以从表达式直接使用。

That being said, if you only want two parameters (or one or three), there is an overload of string.Format() that you can use directly from an expression.

这篇关于调用与表达(params对象[])[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆