gpt4 book ai didi

c# - int[] 使用 "wrong"Console.WriteLine 重载

转载 作者:太空狗 更新时间:2023-10-29 17:43:06 24 4
gpt4 key购买 nike

我和一位同事一起研究一些基本的 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结构有什么不同吗?如果是,为什么?

编辑

我用相同格式的 double 进行了快速测试,但效果不佳,这让我认为类型确实是一个结构,但我仍然不明白为什么这会有所不同.

最佳答案

这适用于 string 对象的原因是 Array Covariance C#的特性。

For any two reference-types A and B, if an implicit or explicit reference conversion exists from A to B, then the same reference conversion also exists from the array type A[] to the array type B[]

存在从stringobject 的隐式转换,因此WriteLine 将您的string[] 数组放入object[] 数组的位置。

int[] 没有协方差,因为 int 不是引用类型。如果你想使用显式转换,你可以这样做:

object[] ints = (new int[]{ 1,2,3 }).Cast<object>().ToArray();
Console.WriteLine("{0}, {1}, {2}", ints);

Demo.

关于c# - int[] 使用 "wrong"Console.WriteLine 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34775510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com