mar*_*n36 15 .net c# arrays string string-formatting
当尝试使用数组作为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);
Run Code Online (Sandbox Code Playgroud)
Array包含四个值,其中的参数String.Format()也相同.
是什么导致这个错误?
(这infoText.text只是一个常规的String对象)
Bal*_*thu 10
你可以将int数组转换为字符串数组.
infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}",
place.Select(x=>x.ToString()).ToArray());
Run Code Online (Sandbox Code Playgroud)
快速解决.
var place = new object[] { 1, 2, 3, 4 };
Run Code Online (Sandbox Code Playgroud)
C#不支持共变阵列转换int[],object[]因此整个数组被认为是object,因此调用具有单个参数的这种重载.
可以为params参数传递显式数组,但它必须具有匹配类型.string.Format有一些重载,其中以下两个对我们很有意思:
string.Format(string, params object[])
string.Format(string, object)
Run Code Online (Sandbox Code Playgroud)
在你的情况下,处理int[]as object是唯一有效的转换,因为int[]无法隐式(或显式)转换为object[],所以string.Format看到四个占位符,但只有一个参数.您必须声明正确类型的数组
var place = new object[] {1,2,3,4};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23948 次 |
| 最近记录: |