[英]list object of struct is never assigned to and will always have its default value null
How should I initialize a List of a struct. 我应该如何初始化结构列表。 Struct can be initialized, but by just using my list here it says: Folder is never assigned to and will always have its default value null
可以初始化结构,但是仅使用此处的列表便会说:文件夹从未分配给它,并且始终具有其默认值null
private struct directories
{
public List<string[]> Folder;
}
directories d1 = new directories();
d1.Folder.Add(Directory.GetDirectories(path1));
The problem with structs is that their constructor is not guaranteed to run. 结构的问题是不能保证其构造函数运行。 Eg, when you create an array
var array = new directories[10];
例如,当您创建一个数组时,
var array = new directories[10];
. 。 Therefore structs cannot have initializers and explicit parameterless constructors.
因此,结构不能具有初始化程序和显式的无参数构造函数。
In this example I use lazy initialization to ensure the folder list to be initialized. 在此示例中,我使用延迟初始化来确保要初始化文件夹列表。
private struct directories
{
private List<string[]> _folder;
public List<string[]> Folder
{
get {
if (_folder == null) {
_folder = new List<string[]>();
}
return _folder;
}
}
}
But in this case I would simply use the existing DirectoryInfo Class from the System.IO
namespace. 但是在这种情况下,我将只使用
System.IO
名称空间中现有的DirectoryInfo类 。 It does this and much more for you. 它可以为您完成更多任务。 Don't reinvent the wheel.
不要重新发明轮子。
DirectoryInfo rootDir = new DirectoryInfo(path1);
DirectoryInfo[] directories = rootDir.GetDirectories("*", SearchOption.AllDirectories);
Both, GetDirectories
and GetFiles
have overloads allowing you to specify search patterns and whether you want to recurse subdirectories. GetDirectories
和GetFiles
都有重载,允许您指定搜索模式以及是否要递归子目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.