将数组作为参数传递 [英] Passing an array as `params` argument

查看:107
本文介绍了将数组作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

void MyMethod(params object[] args)
{
}

我正在尝试使用类型为object[]的参数进行调用:

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

object[] myArgs = GetArgs();
MyMethod(myArgs);

它可以编译,但是在MyMethodargs == { 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);

... 然后打印1,因为它实际上是在调用MyMethod(new object[] { args }).

... then it prints 1, because it's effectively calling MyMethod(new object[] { args }).

这篇关于将数组作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆