为什么String.Format有区别待遇?

3

String.Format可以正确地处理字符串数组,但在处理整数数组时会出现以下异常:

索引(从零开始)必须大于或等于零,并且小于参数列表的大小。

        string result = null;
        var words = new string[] { "1", "2", "3" };
        result = String.Format("Count {0}{1}{2}", words); //This works.

        var nums = new int[] { 1, 2, 3 };
        result = String.Format("Count {0}{1}{2}", nums); //This throws an exception.

为什么会这样呢?
2个回答

7
这是因为你使用的 string.Format 重载需要 object[]string 是引用类型,所以 string[] 可以隐式转换为 object[],但是 int 是值类型,必须进行装箱才能放入对象数组中。因此,当你使用 int 时,它会选择另一个只接受一个参数的重载,然后将整个 int[] 作为单个对象传递,而不是按照每个 int 单独传递。

4
由于调用了整数数组的ToString()方法,因此它变成了一个对象。 以下是代码:
var nums = new int[] { 1, 2, 3 };
result = String.Format("Count {0}", nums);

将会得到结果:计数 System.Int32[]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接