【问题标题】:params keyword taking an array as a single parameter interprets the contents of the array as all its parameters将数组作为单个参数的 params 关键字将数组的内容解释为其所有参数
【发布时间】:2016-12-05 18:19:48
【问题描述】:

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

    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);,会产生预期的结果(加上空字符串),因此这可能是解决此问题的一种方法,但是就我而言,这既不优雅也不是一个好主意。从文档的内容来看,这不应该发生。是否有任何优雅的解决此问题的方法?

【问题讨论】:

标签: c# arrays params


【解决方案1】:

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

查看此答案以了解发生了什么:C# params object[] strange behavior

【讨论】:

    【解决方案2】:

    您可以将参数转换为object

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

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 2016-06-06
      相关资源
      最近更新 更多