【发布时间】: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);,会产生预期的结果(加上空字符串),因此这可能是解决此问题的一种方法,但是就我而言,这既不优雅也不是一个好主意。从文档的内容来看,这不应该发生。是否有任何优雅的解决此问题的方法?
【问题讨论】:
-
是的,我认为是 :( 不幸的是,在发布我的问题之前进行研究时,我没有看到该帖子。