问题描述
我有以下方法:
void MyMethod(params object[] args)
{
}
我试图用 object[]
类型的参数调用它:
which I am trying to call with a parameter of type object[]
:
object[] myArgs = GetArgs();
MyMethod(myArgs);
它编译得很好,但在 MyMethod
内部我 args == { myArgs}
,即一个数组,其中一个元素是我的原始参数.显然我想要 args = myArgs
,我做错了什么?
It compiles fine, but inside MyMethod
I args == { myArgs}
, i.e. an array with one element that is my original arguments. Obviously I wanted to have args = myArgs
, what am I doing wrong?
Jon Skeet 实际上是对的,GetArgs()
确实将这个东西包装在一个单元素数组中,抱歉问了一个愚蠢的问题.
Jon Skeet was actually right, the GetArgs()
did wrap the thing in an one element array, sorry for stupid question.
推荐答案
你所描述的根本没有发生.除非需要,编译器不会不创建包装器数组.这是一个简短但完整的程序来演示这一点:
What you've described simply doesn't happen. The compiler does not create a wrapper array unless it needs to. Here's a short but complete program demonstrating this:
using System;
class Test
{
static void MyMethod(params object[] args)
{
Console.WriteLine(args.Length);
}
static void Main()
{
object[] args = { "foo", "bar", "baz" };
MyMethod(args);
}
}
根据您的问题,这会打印 1 - 但它不会打印 3.args
的值直接传递给 MyMethod
,没有进一步扩展.
According to your question, this would print 1 - but it doesn't, it prints 3. The value of args
is passed directly to MyMethod
, with no further expansion.
要么您的代码与您发布的不同,要么包装"发生在 GetArgs
中.
Either your code isn't as you've posted it, or the "wrapping" occurs within GetArgs
.
您可以通过将 args
强制转换为 object
来强制包裹它.例如,如果我将 Main
的最后一行更改为:
You can force it to wrap by casting args
to object
. For example, if I change the last line of Main
to:
MyMethod((object) args);
... then 它打印 1,因为它有效地调用了 MyMethod(new object[] { args })
.
... then it prints 1, because it's effectively calling MyMethod(new object[] { args })
.
这篇关于将数组作为 `params` 参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!