Passing an array as `params` argument

99封情书 提交于 2019-11-28 03:24:06

问题


I have the following method:

void MyMethod(params object[] args)
{
}

which I am trying to call with a parameter of type object[]:

object[] myArgs = GetArgs();
MyMethod(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?

EDIT:
Jon Skeet was actually right, the GetArgs() did wrap the thing in an one element array, sorry for stupid question.


回答1:


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

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.

Either your code isn't as you've posted it, or the "wrapping" occurs within GetArgs.

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 it prints 1, because it's effectively calling MyMethod(new object[] { args }).



来源:https://stackoverflow.com/questions/21704990/passing-an-array-as-params-argument

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