使用数组作为string.Format()的参数 [英] Using an array as argument for string.Format()

查看:1442
本文介绍了使用数组作为string.Format()的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试将数组用作 string.Format()方法的参数时,出现以下错误:

When trying to use an array as an argument for the string.Format() method, I get the following error:


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

FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

代码如下:

place = new int[] { 1, 2, 3, 4};
infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place);

数组包含四个值和 String.Format()中的参数也相同。

The Array contains four values and the arguments in the String.Format() are also the same.

什么原因导致此错误?

( code> infoText.text 只是一个常规的String对象)

(The infoText.text is just a regular String object)

推荐答案

您可以转换使用 System.Linq Select()扩展方法将int数组传递为字符串数组。

You can convert int array to string array as pass it using System.Linq Select() extension method.

infoText.text = string.Format("Player1: {0} \nPlayer2: {1} \nPlayer3: {2} \nPlayer4: {3}", 
                              place.Select(x => x.ToString()).ToArray());

编辑:

在C#6及更高版本中,您还可以使用 字符串插值 而不是使用 string.Format()

In C# 6 and above, you can also able to use String Interpolation instead of using string.Format()

infoText.text = $"Player1: {place[0]}\nPlayer2: {place[1]} \nPlayer3: {place[2]} \nPlayer4: {place[3]}";

选中此提琴供您参考。

这篇关于使用数组作为string.Format()的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆