Passing an array as `params` argument

前端 未结 1 366
日久生厌
日久生厌 2020-12-19 01:04

I have the following method:

void MyMethod(params object[] args)
{
}

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

相关标签:
1条回答
  • 2020-12-19 01:41

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

    0 讨论(0)
提交回复
热议问题