String.Format:Index(从零开始)必须大于或等于零且小于参数列表

时间:2015-11-15 23:57:37

标签: arrays vb.net string

我尝试使用值数组格式化字符串:

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

1 个答案:

答案 0 :(得分:2)

为什么使用Object作为args的类型?你只是扔掉了所有的类型信息。

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)只是一个表达式{{1}并且不会神奇地改变T的类型,即使你转换为正确的类型)并将其视为单元素数组。

您可能也需要使用args。我无法检查。