C# 数组索引总是超出

标签 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,因此尝试获取 > 0 的索引会失败。

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

感谢所有提供帮助的人 - 抱歉,我只能选择一个正确答案。

最佳答案

if (bedProperties.Length > 0)

应该是:

if(bedProperties.Length > 1)

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

关于C# 数组索引总是超出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8304092/

相关文章:

c# - 什么是基于规则的算法?

c# - 如果文件不存在,Asp.net FileStream Create 会抛出错误

javascript - 从对象数组创建树层次结构

javascript - 使用indexOf获取数组集合中数组的索引(Javascript)

Javascript/jQuery 获取 iFrame 索引

mysql - INNER JOIN 的查询优化

c# - 开发存储账户需要身份验证

C# - 将数字四舍五入为 0 位小数

c++ - 在 C++ 中初始化指针数组

mysql - 有什么改进 MySQL 查询的技巧吗?