如何防止阵列超出范围?

时间:2019-05-08 12:09:23

标签: c#

这里有一些代码。当不断增加并循环查找另一个文件名时,如何防止它超出范围

int deleteIndex = 0;

FileSystemInfo[] fileInfo = new DirectoryInfo(basepath)
  .GetFileSystemInfos()
  .OrderBy(fi => fi.CreationTime)
  .ToArray();

while (fileInfo[deleteIndex].Name.StartsWith("GDZ"))
{
    deleteIndex++;

    //if index out of range, cancel delete folder
    if (fileInfo.Count() <= deleteIndex) 
        return;
}

2 个答案:

答案 0 :(得分:0)

if (deleteIndex<fileInfo .Length)

答案 1 :(得分:-1)

fileInfo为空时fileInfo[0]将引发异常。下面的代码可以解决问题;

while (fileInfo.Length > 0 && fileInfo[deleteIndex].Name.StartsWith("GDZ"))
        {
            deleteIndex++;

            //if index out of range, cancel delete folder
            if (fileInfo.Count() <= deleteIndex) 
            return;
        }