vb.net csharp 中的 foreach 语句 ERROR 中都需要类型和标识符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15165795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type and identifier are both required in a foreach statement ERROR in csharp
提问by Peter Jennings
I am converting VB.net to C# for this code:
我正在将此代码的 VB.net 转换为 C#:
Dim files() As String
files = Directory.GetFiles("E:\text", "*.txt")
Dim filename As String
Dim file As String
For Each file In files
filename = Path.GetFileName(file)
I tried this in C# but got the error
我在 C# 中尝试过这个,但得到了错误
Type and identifier are both required in a foreach statement ERROR in csharp
csharp 中的 foreach 语句 ERROR 中都需要类型和标识符
string[] files;
files = Directory.GetFiles("E:\text", "*.txt");
string[] filenameMove;
string filename;
string file;
foreach (file in files)
filename = Path.GetFileName(file);
回答by Brandon
Try
尝试
foreach(var file in files)
You need to specify the type you're looping through or use var
您需要指定循环或使用的类型 var
You already declared a variable called file though. So you'd have to use a different name
不过,您已经声明了一个名为 file 的变量。所以你必须使用不同的名字
foreach(var f in files)
{
filename = Path.GetFileName(f);
}
(Although with your logic you're just overwriting the filename on each iteration, so unless you only want the last filename, I'm not sure what the purpose of it is).
(虽然按照你的逻辑,你只是在每次迭代时覆盖文件名,所以除非你只想要最后一个文件名,否则我不确定它的目的是什么)。
回答by syed mohsin
You should take a look at foreachsyntax.
你应该看看foreach语法。
Foreach(Type varName in array)
{
filename = Path.GetFileName(varName);
}
that Typeand array should be of same Typeor you could use varvariable like this
那Type和数组应该相同,Type或者你可以使用这样的var变量
Foreach(var varName in array)
{
filename = Path.GetFileName(varName);
}
回答by DOT.NET
That here are u missing var and string
你在这里缺少 var 和 string
try this
尝试这个
foreach (var file in files)
foreach (string file in files)
回答by saeed
string[] files;
files = Directory.GetFiles("E:\text", "*.txt");
string[] filenameMove;
string filename;
//string file;
//foreach (file in files)
foreach (string file in files)
filename = Path.GetFileName(file);

