Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - Passing an array as `params` argument

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...