【问题标题】:Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the size of the argument list."使用 String.Format 时出现异常“索引(从零开始)必须大于或等于零且小于参数列表的大小。”
【发布时间】:2015-02-27 13:50:01
【问题描述】:

我有一个数组

ArrayList array = new ArrayList();
array.Add("a");
array.Add("b");
array.Add("c");

我有一个字符串变量 refFormat,其格式如下。

string refFormat = "{2} {0}";

我正在尝试从具有这种格式的数组中获取一串值。下面是我写的。

string newStr = String.Format(refFormat,array.ToArray());

我在尝试执行此操作时遇到以下异常。

索引(从零开始)必须大于或等于零且小于参数列表的大小。

我知道这个问题听起来很重复,但我的疑问是如何从索引以 20 格式指定的索引的数组中选择值。请帮忙..

编辑:您好,很抱歉提出了错误的问题。我正在使用数组列表而不是字符串数组,我正在尝试相同的方法。尽管使用 ToArray() 将其转换为数组,但我仍然遇到异常。我哪里错了?而且我不能在这里使用 List 而不是 arraylist 因为数组包含不同类型的数据。请帮帮我..

【问题讨论】:

  • 你确定你在string newStr = String.Format(refFormat,array); 行得到这个异常吗? It shouldn't throw any excetion based on your codenewStr 将是 c a
  • 我只是试图重现该错误,但我的代码有效。我使用了与您的问题完全相同的代码,我没有做任何更改。
  • 好吧,这段代码运行良好:dotnetfiddle.net/sQUxiu
  • 其实我用的是 ArrayList 而不是 string[]。这可能是它失败的原因吗?
  • @AkshathaPatil,当然这是原因。 ArrayList 属于不同的重载,我相信 Format(string, object)。这也是为什么建议大家将实际代码放入问题中的原因

标签: c# arrays string.format


【解决方案1】:

作为参考,这也是我的工作代码:

string[] array = new string[] { "a", "b", "c", "d" };

string refFormat = "{2} {0}";

string newStr = String.Format(refFormat, array);

Console.WriteLine(newStr);

我在运行上述代码时没有遇到错误。

【讨论】:

    【解决方案2】:

    你没有正确给出参数,它需要被索引为 {0} {1} 等等

    String.Format(refFormat,array[2],array[0]);
    

    【讨论】:

    • 两者都是按照 OP 要求做的有效方法。
    猜你喜欢
    • 2023-04-11
    • 2011-04-18
    • 2011-12-19
    • 2016-07-03
    • 2016-04-01
    • 2018-07-26
    • 2016-04-13
    • 2011-11-20
    相关资源
    最近更新 更多