Passing an array as `params` argument

雨燕双飞 提交于 2019-11-29 10:26:53

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

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