(C#) FileInfo 数组越界异常...除非它不是
代码:
DirectoryInfo[] d2 = new DirectoryInfo[400];
d2 = moreDirect.GetDirectories();
//Declaring FileInfo array
FileInfo[] f = new FileInfo[300];
f = d2[z].GetFiles();
if (d2[z].Exists)
{
if (f[y] != null)
{
...
//FileInfo does it stuff and somewhere it does ++y depending on the situation blahblahblah
if (f[y] == null) <-------- Right here is where it does it! And y only equals 1 here. I checked.
{
y = 0;
fileTime = false;
break;
}
那么,有人知道出了什么问题吗?我绞尽脑汁了。我用谷歌搜索过,我搜索过堆栈溢出。这一定是一些愚蠢的事情。我不知道。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
GetFiles() 返回一个新数组。之前将 f 声明为大小为 300 的数组并不重要,当 GetFiles 返回时,它会使用新数组重新分配 f,而旧的大小为 300 的数组会丢失。
实际上,您根本不需要创建数组,只需这样做即可。
当您需要访问它时,您应该首先检查数组长度或使用 for/foreach 循环来迭代数组中的每个项目。
GetFiles() returns a new array. It doesn't matter that you declared f to be an array of size 300 just before, when GetFiles returns it reassigns f with the new array and the old size 300 one is lost.
You actually don't need to create the array at all, you can just do this.
When you need to access it you should check the arrays length first or use a for/foreach loop to iterate over each item in the array.
您正在将另一个数组重新分配给您的
f
变量。d2[z].GetFiles();
返回的数组中只有一个元素可能会导致您的问题(第一个if
条件中 y == 0 并且 y = = 1 在第二个)。You are reassigning another array to your
f
variable. Having just one element in the array returned byd2[z].GetFiles();
, may cause your problem (y == 0 in the firstif
condition and y == 1 in the second).数组中索引 1 处不能有元素,为了安全起见,您应该使用
foreach
或for (int i=0;i 永远不要尝试访问数组元素,除非您已经以编程方式确认了它的存在。
There must not be an element at index 1 in the array, to be safe you should iterate over the array using
foreach
orfor (int i=0;i<array.length;i++)
never try to access an array element unless you have programatically confirmed it's existence.