我正在与一位同事一起研究一些基本的C#教程,尽管遇到了一个有趣的难题,但我们遇到了。
以下代码按预期工作:
string[] strings = { "1", "2", "3" };
Console.WriteLine("{0}, {1}, {2}", strings);
它获取字符串数组,并使用方法的Console.WriteLine(string format, params object[] arg)
重载将字符串“ 1、2、3”输出到控制台WriteLine
。
但是,以下代码不起作用:
int[] ints = { 1, 2, 3 };
Console.WriteLine("{0}, {1}, {2}", ints);
您会收到一条FormatException
消息,Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
使用Intellisense,我可以看到它正在尝试使用Console.WriteLine(string format, object arg0)
重载,这就是我们收到该消息的原因,ints
尽管它显然是一个数组,但它并没有被视为数组。
如果我们切换到更明显的位置:
int[] ints = { 1, 2, 3 };
Console.WriteLine("{0},{1},{2}", ints[0], ints[1], ints[2]);
它可以再次工作并再次使用params object[]
过载。
是否有原因将其int[]
视为方法的数组?Int32
结构的事实会有所作为吗?如果是这样,为什么?
编辑
我用相同的格式对双精度进行了快速测试,但也没有用,这让我认为这确实是类型是struct的事实,但我仍然不明白为什么这样做会有所作为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句