Преобразовать Node в строку и наоборот - C#
Формулировка задачи:
имеется класс
класс формирует древовидную структуру,
задача состоит в следующем, нужно сформированное дерево преобразовать в object или строку, передать клиенту(с этим я справлюсь), затем у клиента из object или строки опять получить древовидную структуру
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CustomTree { public class Node { public Node() { _children = new NodeCollection(this); } public Node(string name) { _children = new NodeCollection(this); this.Name = name; } public Node AddNode(string name) { var rv = new Node(name); this.Children.Add(rv); return rv; } Node _parent; public Node Parent { get { return _parent; } set { if (Parent != null || value == null) { Parent.Children.Remove(this); } else { value.Children.Add(this); } _parent = value; } } public string Name { get; set; } NodeCollection _children; public override string ToString() { var rv = new StringBuilder(Name); foreach (Node ch in Children) { SubNodeToString(ch, rv); } return rv.ToString(); } public int Level { get { return Parent != null ? this.Parent.Level + 1 : 0; } } void SubNodeToString(Node n, StringBuilder sb) { sb.Append("\n" + repeat("\t", n.Level)); sb.Append(n.Name); sb.Append(string.Format(" (Parent: {0})", n.Parent.Name)); foreach (Node ch in n.Children) { SubNodeToString(ch, sb); } } string repeat(string s, int count) { var rv = new StringBuilder(); for (int i = 0; i < count; i++) { rv.Append(s); }; return rv.ToString(); } public NodeCollection Children { get { return _children; } } public class NodeCollection : System.Collections.ObjectModel.Collection<Node> { internal NodeCollection(Node owner) { _owner = owner; } Node _owner; protected override void InsertItem(int index, Node item) { if (!this.Contains(item)) { base.InsertItem(index, item); item._parent = _owner; } } protected override void RemoveItem(int index) { this[index]._parent = null; base.RemoveItem(index); } } } }
var root = new Node("root"); var c1 = root.AddNode("child1"); var c2 = root.AddNode("child2"); var c1_1 = c1.AddNode("child1_1"); var c1_2 = c1.AddNode("child1_2"); var c2_1 = new Node("child2_1"); c2_1.Parent = c2; var c2_2 = c2.AddNode("child2_2"); Console.Write(root.ToString()); Console.WriteLine("\n"); Console.WriteLine("Удаляем узлы\n"); c2.Children.Remove(c2_2); c2_1.Parent = null; Console.WriteLine(root.ToString()); Console.ReadKey();
Решение задачи: «Преобразовать Node в строку и наоборот»
textual
Листинг программы
class B {A[] b;}
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д