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
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];
. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.