[英]C# Class with recursion
我正在嘗試創建一個其中包含“項目”列表的類。 我已成功完成此操作,但是隨后我想在項目列表中創建項目列表。 我也能夠做到這一點,但是我必須為該項目中的類使用其他名稱。
我想使用相同的類名,因為它將用於生成一些其中類名很重要的json。 另外,我希望能夠以一種像文件夾結構一樣遞歸的方式來執行此操作。 每個屬性的所有屬性都相同。 我希望我已經解釋得足夠好了。 我實質上是在嘗試創建一個文件夾/文件結構,其中每個文件夾中可以有x個文件,也可以有x個文件夾,依此類推。
例如:
DocLib
-項目
--Item.Items
--- Item.Items.Items
--Item.Items
-項目2等...
這是現有的代碼:
public class DocLib
{
public string Title { get; set; }
public string spriteCssClass { get { return "rootfolder"; } }
public List<item> items { get; set; }
public DocLib()
{
items = new List<item>();
}
public class item
{
public string Title { get; set; }
public string spriteCssClass { get; set; }
public List<document> documents { get; set; }
public item()
{
documents = new List<document>();
}
public class document
{
public string Title { get; set; }
public string spriteCssClass { get; set; }
}
}
}
我相信可能有更好的方法來實現這一點。
只是讓項目成為您自己的類型的列表
public class DocLib{
public string Title { get; set; }
public string spriteCssClass { get { return "rootfolder"; } }
List<DocLib> _items;
public DocLib(){
_items = new List<DocLib>();
}
public List<DocLib> Items {
get{
return _items;
}
}
}
編輯用法示例:
public static class DocLibExtensions {
public static void Traverse(this DocLib lib,Action<DocLib> process) {
foreach (var item in lib.Items) {
process(item);
item.Traverse(process);
}
}
}
class Program {
static void Main(string[] args) {
DocLib rootDoc = new DocLib {Title = "root"};
rootDoc.Items.Add( new DocLib{ Title = "c1" });
rootDoc.Items.Add(new DocLib { Title = "c2" });
DocLib child = new DocLib {Title = "c3"};
child.Items.Add(new DocLib {Title = "c3.1"});
rootDoc.Items.Add(child);
rootDoc.Traverse(i => Console.WriteLine(i.Title));
}
}
您也可以使用泛型執行此操作。
public class DocLib<T>
{
public T Item { get; set; }
public IEnumerable<DocLib<T>> Items { get; set; }
}
public class Item
{
public string Title { get; set; }
public string spriteCssClass { get; set; }
}
//Usage
//Set up a root item, and some sub-items
var lib = new DocLib<Item>();
lib.Item = new Item { Title="ABC", spriteCssClass="DEF" };
lib.Items = new List<DocLib<Item>> {
new DocLib<Item>{ Item = new Item {Title="ABC2", spriteCssClass="DEF2"} },
new DocLib<Item>{ Item = new Item {Title="ABC3", spriteCssClass="DEF3"} }
};
//Get the values
var root = lib.Item;
var subItems = lib.Items.Select(i=>i.Item);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.