C#:将集合转换为 params[]
以下是我的代码的简化:
void Foo(params object[] args)
{
Bar(string.Format("Some {0} text {1} here {2}", /* I want to send args */);
}
string.Format
要求将参数作为 params
发送。有什么方法可以将 args 集合转换为 string.Format 方法的参数吗?
Here is a simplification of my code:
void Foo(params object[] args)
{
Bar(string.Format("Some {0} text {1} here {2}", /* I want to send args */);
}
string.Format
requires the arguments sent as params
. Is there some way I can convert the args
collection into parameters for the string.Format
method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
params
关键字只是语法糖,它允许您使用任意数量的参数调用此类方法。但是,这些参数始终作为数组传递给该方法。这意味着
Foo(123, "hello", DateTime.Now)
相当于Foo(new object[] { 123, "hello", DateTime.Now })
。因此,您可以将参数从
Foo
直接传递到string.Format
,如下所示:但是,在这种特殊情况下,您需要三个参数(因为您有 {0}、{ 1} 和 {2}(按照您的格式)。因此,您应该将代码更改为:
...或按照马塞洛的建议进行操作。
The
params
keyword is only syntactic sugar that allows you to call such a method with any number of arguments. However, those arguments are always passed to the method as an array.This means that
Foo(123, "hello", DateTime.Now)
is equivalent toFoo(new object[] { 123, "hello", DateTime.Now })
.You can therefore pass the arguments from
Foo
directly tostring.Format
like this:However, in this particular case, you demand three arguments (because you have {0}, {1} and {2} in your format). Therefore you should change your code to:
...or do as Marcelo suggested.
将它们作为单个参数传递:
Pass them in as a single argument:
例如,您可以尝试使用 object.GetType()
You could try using object.GetType(), for example