params 关键字将数组作为单个参数,将数组的内容解释为其所有参数

params keyword taking an array as a single parameter interprets the contents of the array as all its parameters

我已经使用 params 关键字编写了一个简单的程序来获取参数并将它们写入控制台。当我将单个数组传递给带有 params 标记的参数时,我 want/expect 会发生什么,以及 C# documentation states 会发生什么是该数组将成为 [= 中的第一个元素13=]数组。这是一些示例代码:

    public static void Main()
    {
        Paramtest(new object[] { "hi", "wow", 78 });
        Console.ReadKey();
    }

    public static void Paramtest(params object[] args) {
        foreach (object o in args) {
            Console.WriteLine("{0} is a type of {1}.", o.ToString(), o.GetType());
        }
    }

应该看到的是控制台上的一行文字:

System.object[] is a type of System.object[].

做的看到的是三行字:

hi is a type of System.String.
wow is a type of System.String.
78 is a type of System.Int32.

我发现在数组后使用另一个参数调用 Paramtest,例如:Paramtest(new object[] { "hi", "wow", 78 }, String.Empty);,会产生预期的结果(加上空字符串),所以这可能是一种方法解决这个问题,但在我的情况下这不是优雅或好主意。根据文档所说,这不应该发生。这个问题有优雅解决方法吗?

您可以将参数转换为 object:

public static void Main()
{
    Paramtest((object)new object[] { "hi", "wow", 78 });
    Console.ReadKey();
}

我同意您在文档中指出的示例代码可能会导致一些混乱。此处您使用的是 Object 数组,而该示例使用的是 Integer 数组,其处理方式不同。

查看此答案以了解发生了什么: