2015-11-15 132 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

相关问题