我在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#不太熟悉,所以如果我犯了一些非常愚蠢的错误,请不要过于苛刻。
谢谢 - 我非常感谢所有的帮助。
编辑:根据下面许多帮助,我找到了问题。
为了清楚起见,这是整个函数:
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的索引将失败。
顺便说一下,这是一个变换内部的扩展方法,这就是以一个大字符串作为初始集合的原因。
感谢所有帮助过我的人 - 很抱歉我无法选择多个正确答案。
bedProperties[1]
,那么您应该检查bedProperties.Length > 1
是否成立...这不可能存在 bayBeds 中有一张床只有一个属性而导致异常的情况吗? - fwalch