gpt4 book ai didi

C# 数组索引总是超出

转载 作者:行者123 更新时间:2023-11-30 13:40:17 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com