Csharp/C#教程:使用数组作为string.Format()的参数分享


使用数组作为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().ToArray() ); 

顺便说一句,如果您使用的是C#6或更高版本,您可以考虑使用插值字符串而不是string.Format

上述就是C#学习教程:使用数组作为string.Format()的参数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 infoText.text = $"Player1: {place[0]}n Player 2: {place[1]} n Player 3: {place[2]} n Player 4: {place[3]}"; 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/954279.html

(0)
上一篇 2021年11月20日
下一篇 2021年11月20日

精彩推荐