[英]Warning: Field is never assigned to, and will always have its default value null
[英]list object of struct 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));
結構的問題是不能保證其構造函數運行。 例如,當您創建一個數組時, var array = new directories[10];
。 因此,結構不能具有初始化程序和顯式的無參數構造函數。
在此示例中,我使用延遲初始化來確保要初始化文件夾列表。
private struct directories
{
private List<string[]> _folder;
public List<string[]> Folder
{
get {
if (_folder == null) {
_folder = new List<string[]>();
}
return _folder;
}
}
}
但是在這種情況下,我將只使用System.IO
名稱空間中現有的DirectoryInfo類 。 它可以為您完成更多任務。 不要重新發明輪子。
DirectoryInfo rootDir = new DirectoryInfo(path1);
DirectoryInfo[] directories = rootDir.GetDirectories("*", SearchOption.AllDirectories);
GetDirectories
和GetFiles
都有重載,允許您指定搜索模式以及是否要遞歸子目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.