當試圖使用數組作爲參數爲string.Format()
方法,我得到以下錯誤:使用數組作爲參數對的String.format()
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()
中的參數也相同。
是什麼導致了這個錯誤?
(該infoText.text
只是一個普通的字符串對象)
你傳遞一個' int []'而不是'string []' –
也許像'string.Format(「Player1:{0} \ n Player2:{1} \ n Player3:{2} \ n Player4:{3}」 ,[0],位置[1],位置[2],位置[3]);' 當你傳遞一個與字符串中每個{}有關的對象時,它就起作用 – Awais
只是爲了記錄而不是使用string.format,你可以創建該字符串更動態,不需要硬編碼玩家數量,例如:'infoText.text = string.Join(「\ n」,place.Select((p,i)=> $「Player {i + 1}:{p} 「));' –