问题描述
我被要求返回包含给定目录中所有文件名的集合(不包括子目录) 。我试过的代码如下。它应该是正确的,因为 myPath.AsDirectory()。GetFiles()
方法返回目录包含的文件列表(不包括子目录)。
现在,我在返回旁边的路径一词下方有一条红色的波浪线。它说'不能隐含地将'string'类型转换为'Systems.Collections.Generic.IEnumerable< string>'为什么会这样?我该如何修复代码?
亲切的问候
我尝试了什么:
Hi,
I have been asked to Return a collection containing all the file names within the given directory (not including subdirectories). The code I have tried is below. It should be correct because the myPath.AsDirectory().GetFiles()
method returns a list of files contained by the directory (excluding sub-directories).
Right now, I have a red squiggly line underneath the word 'path' next to return. It says 'cannot implicitly covert type 'string' to 'Systems.Collections.Generic.IEnumerable<string>' Why is this? How can I fix the code?
Kind regards
What I have tried:
public static IEnumerable<string> GetFiles(string path)
{
path.AsDirectory().GetFiles();
return path;
}
推荐答案
public static IEnumberable<string> GetFiles(string path)
{
return Directory.GetFiles(path);
}
public static IEnumerable<string> GetFiles(string path)
{
return path.AsDirectory().GetFiles();
// I don't know where you found this extension for string
}
// I would rewrite it to
public static IEnumerable<string> GetFiles(string path) {
return Directory.GetFiles(path).ToList();
}
这样做就可以了。另请注意,这只返回文件名,而不是目录 - 在System.IO命名空间中有一个不同的函数,查找它。 :-)
最后,只返回列表(为什么要返回一个字符串?显然它应该是所有文件的列表)。
[]
这篇关于C# - 返回包含给定目录中所有文件名的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!