Calling (params object[]) with Expression[]

一世执手 提交于 2019-12-01 04:26:57

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

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();

Here, expressionString will contain this string:

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

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

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 is just syntactic sugar. Ultimately the parameter is just an array. Therefore, the parameter type should be object[] and an expression describing such an array is what you should pass as the second argument. In other words, you should only have two arguments, not three. And the second argument should be a two-element array containing what is currently your 2nd and 3rd arguments.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!