Using an array as argument for string.Format()

好久不见. 提交于 2019-12-19 05:11:24

问题


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

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

The code is as follows:

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

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

What causes this error?

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


回答1:


You can convert int array to string array as pass it.

infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", 
                              place.Select(x=>x.ToString()).ToArray());



回答2:


Quick fix.

var place = new object[] { 1, 2, 3, 4 };

C# does not support co-variant array conversion from int[] to object[] therefor whole array is considered as object, hence this overload with a single parameter is called.




回答3:


It is possible to pass an explicit array for a params argument, but it has to have the matching type. string.Format has a few overloads, of which the following two are interesting to us:

string.Format(string, params object[])
string.Format(string, object)

In your case treating the int[] as object is the only conversion that works, since an int[] cannot be implicitly (or explicitly) converted to object[], so string.Format sees four placeholders, but only a single argument. You'd have to declare your array of the correct type

var place = new object[] {1,2,3,4};



回答4:


As others have already said, you can't convert int[] to object[]. But you can fix this issue using Enumerable.Cast<T>():

infoText.text = string.Format
(
      "Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}",                        
      place.Cast<object>().ToArray()
);

BTW, if you're on C# 6 or above, you might consider using interpolated strings instead of string.Format:

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


来源:https://stackoverflow.com/questions/40885239/using-an-array-as-argument-for-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!