4

试图将一些 VB 转换为 C#...(也学习 C#)。我有一些代码循环遍历目录中的文件并检索它们的文件信息。我最初在 VB 中有这个,但我正在尝试学习 C#,并且在线转换器不给我将通过 .net 2.0 的代码。

这是错误: Type and identifier are both required in a foreach statement

这是我的代码:

DirectoryInfo dirInfo = new DirectoryInfo(currentDir);
FileInfo[] files = null;
files = dirInfo.GetFiles();

FileInfo f = default(FileInfo);
foreach (f in files) {  ...
}

我试过把,foreach(FileInfo f... 但它给了我一个不同的错误: A local variable named 'f' cannot be declared in this scope because it would give a different meaning to 'f', which is already used in a 'parent or current' scope to denote something else

我如何解决它?

4

4 回答 4

13
DirectoryInfo dirInfo = new DirectoryInfo(currentDir);
FileInfo[] files = null;
files = dirInfo.GetFiles();

// I removed the declaration of f here to prevent the name collision.
foreach (FileInfo f in files)
{  ...
}

这是代码的更简单版本:

DirectoryInfo dirInfo = new DirectoryInfo(currentDir);
foreach (FileInfo f in dirInfo.GetFiles())
{
}
于 2012-05-10T21:13:53.577 回答
1

您应该提供循环内使用的变量类型。在您的情况下,它将是FileInfo. 但是使用 C# 3.0 或更高版本,您只需编写var代码,编译器就会为您推断类型:

foreach (FileInfo f in files) 
{  
   // ...
}

在此处阅读有关 foreach 语句的更多信息。

完整的解决方案(您不需要初始化迭代变量和文件数组):

DirectoryInfo dir = new DirectoryInfo(currentDir);
foreach (FileInfo file in dir.GetFiles()) 
{
   // use file  
}
于 2012-05-10T21:13:13.210 回答
1

这就是你看起来出错的地方:

FileInfo f = default(FileInfo);
foreach (f in files) {  ...
}

您在循环外定义 f ,然后尝试在循环内定义它。

如果您需要默认为 f,请尝试以下操作:

FileInfo f = default(FileInfo);
foreach (FileInfo file in files)
    {
         relevant code here
    }

否则删除声明变量“f”的语句

于 2012-05-10T21:22:31.497 回答
0

这应该有效:

        DirectoryInfo dirInfo = new DirectoryInfo(currentDir);
        FileInfo[] files = null;
        files = dirInfo.GetFiles();
        foreach (FileInfo f in files)
        {
        }

编辑:

在我看来,这会更干净:

        foreach (FileInfo f in new DirectoryInfo(currentDir).GetFiles())
            {
            }
于 2012-05-10T21:19:41.687 回答