使用数组作为string.Format()的参数
当尝试使用数组作为string.Format()
方法的参数时,我收到以下错误:
FormatException:Index(从零开始)必须大于或等于零且小于参数列表的大小。
代码如下:
place = new int[] { 1, 2, 3, 4}; infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place);
Array包含四个值, String.Format()
中的参数也相同。
是什么导致这个错误?
( infoText.text
只是一个常规的String对象)
你可以将int数组转换为字符串数组。
infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place.Select(x=>x.ToString()).ToArray());
快速解决。
var place = new object[] { 1, 2, 3, 4 };
C#不支持从int[]
到object[]
共变量数组转换,因此整个数组被视为object
,因此调用具有单个参数的这种重载 。
可以为params
参数传递显式数组,但它必须具有匹配类型。 string.Format
有一些重载,其中以下两个对我们很有意思:
string.Format(string, params object[]) string.Format(string, object)
在你的情况下,将int[]
视为object
是唯一有效的转换,因为int[]
不能隐式(或显式)转换为object[]
,因此string.Format
看到四个占位符,但只有一个参数。 您必须声明正确类型的数组
var place = new object[] {1,2,3,4};
正如其他人已经说过的那样,你不能将int[]
转换为object[]
。 但您可以使用Enumerable.Cast
解决此问题:
infoText.text = string.Format ( "Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place.Cast
顺便说一句,如果您使用的是C#6或更高版本,您可以考虑使用插值字符串而不是string.Format
:
infoText.text = $"Player1: {place[0]}\n Player 2: {place[1]} \n Player 3: {place[2]} \n Player 4: {place[3]}";