【问题标题】:String.Format: Index (zero based) must be greater than or equal to zero and less than the size of the argument listString.Format:索引(从零开始)必须大于或等于零且小于参数列表的大小
【发布时间】:2023-04-11 11:49:01
【问题描述】:

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

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

【问题讨论】:

  • 这是一种特别的语言吗?

标签: arrays vb.net string


【解决方案1】:

为什么使用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) 只是一个产生 T 类型值的表达式,不会神奇地改变类型的args,即使您转换为正确的类型)并将其视为单元素数组。

您可能还需要使用String.Format(mailTemplate, DirectCast(args, Object()))。我无法检查。

【讨论】:

  • 这看起来像我需要的。如何在新字符串数组中保留 3 个空格而无需直接声明其值?我试过了:Dim args(2) As String()Dim args As String() = {,,}Dim args As String(2) Dim args As New String(2)...这些都不对
  • @Flo: Dim args(2) As String
猜你喜欢
  • 2011-04-18
  • 2011-12-19
  • 2016-07-03
  • 2016-04-01
  • 2018-07-26
  • 2011-11-20
  • 1970-01-01
  • 2015-02-27
相关资源
最近更新 更多