我尝试使用值数组格式化字符串:
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)
为什么使用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
。我无法检查。