2015-11-15 90 views
0

我試圖格式化字符串的大小,使用值的數組:的String.Format:(基於零)索引必須大於或等於零且小於參數列表

Dim args(2) As Object 
args(0) = "some text" 
args(1) = "more text" 
args(2) = "and other text" 

Test(args) 

,功能測試是:

Function Test(ByVal args As Object) 
    Dim MailContent as string = "Dear {0}, This is {1} and {2}." 

    'tried both with and without converting arr to Array 
    args = CType(args, Array) 

    MailContent = String.Format(MailContent, args) 'this line throws the error: Index (zero based) must be greater than or equal to zero and less than the size of the argument list. 

End Function 
+0

這是特別的語言嗎? –

回答

2

你爲什麼要使用Objectargs類型?你只是扔掉你的所有類型信息。

Dim args As String() = { 
    "some text", 
    "more text", 
    "and other text" 
} 

Test(args) 
Sub Test(args As String()) 
    Dim mailTemplate As String = "Dear {0}, This is {1} and {2}." 
    Dim mailContent As String = String.Format(mailTemplate, args) 
End Sub 

String.Format接受對象的ParamArray,所以它會讓你通過一個(args; CType(a, T)只是生產T類型的值的表達式,並且不會幻化的類型args即使您轉換爲正確類型)並將其視爲單元素數組。您也許還需要使用String.Format(mailTemplate, DirectCast(args, Object()))。我無法檢查。

+0

這看起來像我需要的東西。如何在新的字符串數組中保留3個空格而不必直接聲明其值?我嘗試: 'Dim args(2)As String()','Dim args As String()= {,,}','Dim args As String(2)','Dim args As New String(2) ...這些都不是正確的 – Flo

+1

@Flo:'Dim args(2)As String' – Ryan

相關問題