C#问题:System.Array.LastIndexOf(myArray,a,b,c)方法好像有BUG啊?大伙快来看看。

msdner 2003-12-11 11:02:32

using System;

class Test
{
public static void Main()
{
int [] myArray = new int [7] {2,1,4,2,15,4,2};

Console.WriteLine(Array.LastIndexOf(myArray,2,5,0));
Console.ReadLine();
}
}

控制台输出值为-1,若把Array.LastIndexOf(myArray,2,5,0)其中的0换成4则会输出3,奇怪了。
...全文
55 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
FileNewExit 2003-12-13
  • 打赏
  • 举报
回复
sorry:

LastIndexOf内部实现的时候可能先判断startIndex和count的关系(startIndex>=count),在满足startIndex>=count的前提下再比较.
FileNewExit 2003-12-13
  • 打赏
  • 举报
回复


Array.LastIndexOf(Array array, Object ob, Int32 startIndex, Int32 count)

就是从array中反向搜索ob,从startIndex开始,搜索count次.

int [] myArray = new int [7] {2,1,4,2,15,4,2};
对应index: 0,1,2,3, 4,5,6

Array.LastIndexOf(myArray,2,5,2) 将比较4和15,皆不为2,返回-1
Array.LastIndexOf(myArray,2,5,4) 将比较4,15,2,到次已经相等了返回3(索引值)Array.LastIndexOf(myArray,2,5,7) 索引5<7,如果比较7个元素,将产生越界.

LastIndexOf内部实现的时候可能先判断startIndex和count的关系(startIndex>=count),在满足startIndex<=count的前提下在比较.

qqchen79 2003-12-12
  • 打赏
  • 举报
回复
So what kind of bug you are talking about?

When the "count" is 0, you are in effect searching backward in an array with zero element. -1 is just the right return.
And if you want to search backward 4 elements, 3 is the index where you can find value 2. Please read MSDN carefully.
cnicq 2003-12-12
  • 打赏
  • 举报
回复
up
baron 2003-12-12
  • 打赏
  • 举报
回复
向后搜索一维 Array,从 startIndex 开始,到 startIndex- count + 1 结束。

这个方法是从后往前开始搜索的。不存在BUG的。楼主可理解上面那句话,然后在程序中多试验几次。
msdner 2003-12-12
  • 打赏
  • 举报
回复
up 一下
FileNewExit 2003-12-12
  • 打赏
  • 举报
回复
Array.LastIndexOf Method (Array array, Object ob, Int32 startIndex, Int32 count)

The one-dimensional Array is searched backward starting at startIndex and ending at startIndex- count + 1.

msdner 2003-12-12
  • 打赏
  • 举报
回复
谢谢各位,我试验了几次,有一点和大家说得好像不太符,可能是vs.net不够智能吧。

using System;

class Test
{
public static void Main()
{
int [] myArray = new int [7] {2,1,4,2,15,4,2};

Console.WriteLine(Array.LastIndexOf(myArray,2,5,0));
Console.WriteLine(Array.LastIndexOf(myArray,2,5,1));
Console.WriteLine(Array.LastIndexOf(myArray,2,5,2));
Console.WriteLine(Array.LastIndexOf(myArray,2,5,3));
Console.WriteLine(Array.LastIndexOf(myArray,2,5,4));
Console.WriteLine(Array.LastIndexOf(myArray,2,5,6));
Console.WriteLine(Array.LastIndexOf(myArray,2,5,7));
Console.ReadLine();
}
}


这样输出的结果为
-1
-1
-1
3
3
3
最后一行导致如下错误:未处理的“System.ArgumentOutOfRangeException”类型的异常出现在 mscorlib.dll 中。

其他信息: endIndex 不能大于 startIndex。//这里提示是endIndex 应该是count吧?
msdner 2003-12-11
  • 打赏
  • 举报
回复
这几天问题好像都没人过目,真是晕,可能是太简单了。

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧