0

代码:

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;
         } 

那么,有谁知道出了什么问题?我绞尽脑汁。我用谷歌搜索,我搜索了堆栈溢出。它必须是愚蠢的。我不知道。

4

3 回答 3

7

GetFiles() 返回一个新数组。之前声明 f 为大小为 300 的数组并不重要,当 GetFiles 返回时,它会使用新数组重新分配 f 并且旧大小为 300 的数组会丢失。

FileInfo[] f = new FileInfo[300];  //<-- Creates a array of size 300.
f = d2[z].GetFiles();              //<-- replaces f with a new array. This array will contain just enough space for the number of files found. 

你实际上根本不需要创建数组,你可以这样做。

FileIndo[] f = d2[z].GetFiles();

当您需要访问它时,您应该首先检查数组长度或使用 for/foreach 循环遍历数组中的每个项目。

于 2009-12-18T23:43:37.287 回答
6
FileInfo[] f = new FileInfo[300];
f = d2[z].GetFiles();

您正在将另一个数组重新分配给您的f变量。, 返回的数组中只有一个元素d2[z].GetFiles();可能会导致您的问题(第一个条件中的 y == 0if和第二个条件中的 y == 1)。

于 2009-12-18T23:42:43.047 回答
2

数组中的索引 1 处不得有元素,为了安全起见,您应该使用迭代数组foreachfor (int i=0;i<array.length;i++)永远不要尝试访问数组元素,除非您以编程方式确认它存在。

于 2009-12-18T23:40:25.030 回答