总是超出C#数组索引

时间:2011-11-28 23:57:28

标签: c# arrays indexing

我在C#中遇到了一个非常奇怪的问题,我不确定是什么原因。请查看以下代码段:

foreach(string bed in bayBeds)
{
    string[] bedProperties = bed.Split(new char[] { '^' });
    if (bedProperties.Length > 0)
    {
        string genderCode = bedProperties[1];
        if (genderCode == "M")
        {
            bedCount = bedCount + bayBeds.Count;
            break;
        }
    }
}

在此示例中,测试字符串数组bedProperties以查看其长度是否大于0,如果是,则检索元素1。问题是此代码总是生成一个越界异常。我可以修改返回bedProperties.Length,它会给我一个值,例如3(实际上是这个对象中的属性数),但是任何尝试通过索引获取数组元素(例如bedProperties [1], bedProperties [0]等)总是给我一个越界异常。的 始终 即可。我不明白为什么会这样。

请理解我是一个c#hack,所以如果我犯了一些可笑的愚蠢错误,请不要过于苛刻。

谢谢 - 我感谢所有帮助。

编辑:我根据以下大部分帮助找到了问题。

为清楚起见,这是整个功能:

public int returnMaleBedTotal(string bedCollection) {
      // determine total number of male beds for a bay
      int bedCount = 0;
      if (bedCollection.Length > 0) {
        List<string> theBays = new List<string>(bedCollection.Split(new char[] { '@' }));

        // at this point we have the bays, so iterate them and extract the beds in the bays
        foreach (string bayBedCollection in theBays) {
          List<string> bayBeds = new List<string>(bayBedCollection.Split(new char[] { '|' }));

          // now we have the beds in the bay, so extract the bed properties and determine if the bed is male
          foreach(string bed in bayBeds) {
            string[] bedProperties = bed.Split(new char[] { '^' });
            if (bedProperties.Length > 1) {
              string genderCode = bedProperties[1];
              string bedStatus = bedProperties[2];
              if (genderCode == "M") {
                bedCount = bedCount + bayBeds.Count;
                break;

              }

            }

          }

        }

      } 

      return bedCount;

    }

这是一个大字符串形式的集合,如下所示:

100000^^3|100002^^1|100003^^3|100004^F^2|100005^^2@100006^^1|100007^^2|100008^M^2|100009^^1|100010^^3@100011^M^2|100012^M^2|100013^M^1|100014^M^2|100015^M^1@100016^F^1|100017^^1|100018^F^1|100019^^1|100020^^1

然后把它切成这样的单位:

100000^^3|100002^^1|100003^^3|100004^F^2|100005^^2

它进一步解析为这样的单位:

100005^^2 or 100004^F^2

有时,在这些迭代过程中,其中一个单位会出现格式错误并且长度为1,因此尝试获得指数&gt; 0会失败。

顺便说一下,这是转换中的扩展方法,这就是将初始集合作为一个大字符串的原因。

感谢所有帮助过的人 - 抱歉,我不能选择一个以上的正确答案。

3 个答案:

答案 0 :(得分:5)

if (bedProperties.Length > 0)

应该是:

if(bedProperties.Length > 1)

因为任何字符串在拆分时都会在单个元素数组中返回。如果实际发生任何分裂,则数组中将有两个或更多元素。

答案 1 :(得分:5)

您遇到的字符串没有^字符:

修复索引:

if (bedProperties.Length > 0) {
  string genderCode = bedProperties[0]; // would take the **first** split element

或条件:

if (bedProperties.Length > 1) {
  string genderCode = bedProperties[1]; // would take the **second** split element

指数从零开始 !!)

答案 2 :(得分:0)

您正在测试if (bedProperties.Length > 0),但您正在访问bedProperties[1]; 您应该检查if (bedProperties.Length > 1)以确保索引1可用。