我有一个表示为父/子关系树的文件夹结构。现在让我们想象下面的树:
- Folder1
---子文件夹1-1
---- Subfolder1-1-1
--- Subfolder2
---- Subfolder2-1
- Folder2
现在我显然要使用导航属性,因此当在Subfolder1-1
内时,我得到了代表ParentFolder
的属性Folder1
。
我现在如何走上树以从文件夹名称中生成连接的字符串?
例如,当从Subfolder1-1-1
调用此方法时,我希望字符串为Folder1.Subfolder1-1.Subfolder1-1-1
,并且在从Subfolder2-1
进行调用时,我希望字符串为Folder1.Subfolder2.Subfolder2-1
。< / p>
我考虑过递归,但以下不起作用:
public string GetCompleteFolderName(string delimiter)
{
string folderName = null;
if (FolderParent != null)
{
folderName += GetCompleteFolderName(FolderParent) + delimiter;
}
return folderName;
}
private string GetCompleteFolderName(Folder folder)
{
string folderName = null;
if (folder != null)
{
folderName = folder.Name;
}
return folderName;
}
答案 0 :(得分:1)
认为这应该做的伎俩
public class Folder
{
public Folder ParentFolder { get; set; }
public string Name { get; set; }
public Folder()
{
}
public string GetFullFolderName(string delimiter = ".")
{
var folderName = string.Empty;
if (ParentFolder != null)
{
folderName += ParentFolder.GetFullFolderName(delimiter) + delimiter + Name;
}
else
{
folderName += Name;
}
return folderName;
}
}
internal class Program
{
private static void Main(string[] args)
{
var f1 = new Folder {Name = "f1"};
var f2 = new Folder {Name = "f2", ParentFolder = f1};
var f3 = new Folder {Name = "f3", ParentFolder = f2};
Console.WriteLine(f3.GetFullFolderName());
}
}
输出:f1.f2.f3