Skip to content

Tutorial3.en

houzkin edited this page Nov 10, 2026 · 4 revisions

Customization by Deriving from the TreeNodeBase Hierarchy

These abstract classes are provided to let you customize tree behavior and the members exposed by the nodes.

TreeNodeBase

Only the properties defined by ITreeNode are exposed, so this class provides a read-only view of the node. It defines protected members to manage the reciprocal references between parent and child nodes when nodes are added or removed. You can customize this behavior by overriding these members in a derived class. You can also expose methods for modifying the tree as needed. TreeNodeBase.cs

public abstract class TreeNodeBase<TNode> : ITreeNode<TNode>
    where TNode:TreeNodeBase<TNode>,ITreeNode<TNode>{

    protected TreeNodeBase() { }

    #region ITreeNode interface
    public TNode? Parent { get; }
    public IEnumerable<TNode> Children { get; }
    #endregion
    
    protected IEnumerable<TNode> ChildNodes;
    
    protected abstract IEnumerable<TNode> SetupInnerChildCollection();

    protected virtual IEnumerable<TNode> SetupPublicChildCollection(IEnumerable<TNode> innerCollection)
        => innerCollection.AsReadOnly();

    protected virtual bool CanAddChildNode(TNode child) { ...}

    protected virtual void InsertChildCore(int index, TNode child,Action<IEnumerable<TNode>,int,TNode>? action = null) {...}

    protected virtual void SetChildCore(int index, TNode child, Action<IEnumerable<TNode>, int, TNode>? action = null) {...}

    protected virtual void RemoveChildCore(TNode child,Action<IEnumerable<TNode>,TNode>? action = null) {...}
    
    protected virtual void ShiftChildCore(int oldIndex,int newIndex,Action<IEnumerable<TNode>,int,int>? action = null) {...}

    protected virtual void ClearChildCore(Action<IEnumerable<TNode>>? action = null) {...}

    protected virtual void Dispose(bool disposing) {...}
}

Customizing the Child Node Collection

  1. The collection specified by SetupInnerChildCollection is assigned to the ChildNodes property.
  2. ChildNodes is the collection directly manipulated by internal operations.
  3. SetupPublicChildCollection takes ChildNodes as its argument, and its return value is exposed externally as Children.

Separating the internal collection from the public collection has the following benefits:

  • You can choose an appropriate collection type for internal use, such as HashSet, LinkedList, or ObservableCollection.
  • It prevents unintended modifications to the child node collection through downcasting.

Here are two customization examples.

Example 1. Use ObservableCollection internally and expose a ReadOnlyObservableCollection.

public class Example1TreeNode : TreeNodeBase<Example1TreeNode> {
    
    protected override IEnumerable<Example1TreeNode> SetupInnerChildCollection() 
        => new ObservableCollection<Example1TreeNode>();

    protected override IEnumerable<Example1TreeNode> SetupPublicChildCollection(IEnumerable<Example1TreeNode> innerCollection) 
        => new ReadOnlyObservableCollection<Example1TreeNode>((innerCollection as ObservableCollection<Example1TreeNode>)!);

    public new ReadOnlyObservableCollection<Example1TreeNode> Children 
        => (base.Children as ReadOnlyObservableCollection<Example1TreeNode>)!;
}

The public collection is exposed through the ITreeNode.Children property, so it is upcast to IEnumerable. To expose it as a ReadOnlyObservableCollection, hide the Children property in the derived class.

Example 2. Use HashSet as the internal collection.

public class Example2TreeNode : TreeNodeBase<Example2TreeNode> {
	protected override IEnumerable<Example2TreeNode> SetupInnerChildCollection()
		=> new HashSet<Example2TreeNode>();
}

Add and Remove Operations

You can specify how child nodes are added to and removed from the collection to match the type of the internal collection. By default, the implementation downcasts ChildNodes to either ICollection or IList during these operations. If the collection specified by SetupInnerChildCollection does not implement either of these interfaces, you need to customize the operations. You can do this through the action argument. Passing null executes the default operation (documented in the XML comments).

alt text

By default, the action argument of InsertChildCore downcasts the internal collection to IList. Therefore, if you use HashSet as the internal collection, as in the example above, customize the method as follows.

public class Example2TreeNode : TreeNodeBase<Example2TreeNode> {
	protected override IEnumerable<Example2TreeNode> SetupInnerChildCollection()
		=> new HashSet<Example2TreeNode>();

	protected override void InsertChildCore(int index, Example2TreeNode child, Action<IEnumerable<Example2TreeNode>, int, Example2TreeNode>? action = null) {
		action ??= (collection, idx, node) => ((ICollection<Example2TreeNode>)collection).Add(node); 
		base.InsertChildCore(index, child, action);
	}
	public Example2TreeNode AddChild(Example2TreeNode child) {
		this.InsertChildCore(0, child);
		return this;
	}
}

This changes the default operation so that it downcasts the collection to ICollection and adds the child, allowing it to work with a HashSet. The reason for using action ??= (collection, idx, node) =>... is to give priority to an operation explicitly specified by another method or by a derived class.

Whether a Child Can Be Added

CanAddChildNode checks whether adding a child would create a cycle or a duplicate among sibling nodes. It is called during the execution of InsertChildCore and SetChildCore.

GeneralTreeNode

A general tree node that exposes methods for adding and removing child nodes. As shown below, it overrides CanAddChildNode to prevent null from being added to the child node collection.

protected override bool CanAddChildNode(TNode child) {
    if (child == null) return false;
    return base.CanAddChildNode(child);
}

Because it implements IMutableTreeNode, editing-related extension methods such as the Try methods are available. This is probably the most convenient class to use when working with tree-structured data.

ObservableGeneralTreeNode

A general tree node that implements IObservableTreeNode. As with GeneralTreeNode, null cannot be added to the child node collection. The ObservableGeneralTreeNode.Children property returns IEnumerable, but the actual instance is a ReadOnlyObservableCollection.

Each node can subscribe to the StructureChanged event to observe which nodes in the tree have changed and how. In addition to information common to all nodes, the event arguments provide AncestorInfo when an ancestor of the subscribed node changes, and DescendantInfo when a descendant changes. ITreeNode.cs

public interface IObservableTreeNode<TNode> : ITreeNode<TNode>
    where TNode : IObservableTreeNode<TNode> {
    /// <summary>Called by <see cref="StructureChangedEventExecutor{TNode}"/> when the tree structure changes.</summary>
    void OnStructureChanged(StructureChangedEventArgs<TNode> e);
    /// <summary>Notification event for when the tree structure changes.</summary>
    event EventHandler<StructureChangedEventArgs<TNode>>? StructureChanged;
}

The following simple class demonstrates the notifications you can receive.

public class ObservableNamedNode: ObservableGeneralTreeNode<ObservableNamedNode> {
    public string Name { get; set; }
    public override string ToString() => this.Name;
}

Create a sample tree and subscribe to each node.

var nodesDic = "ABCDEFGHI".ToCharArray().Select(x => x.ToString()).ToDictionary(x => x, x => new ObservableNamedNode() { Name = x });
var root = nodesDic.Values.AssembleAsNAryTree(2);
Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
├ B
│ ├ D
│ │ ├ H
│ │ └ I
│ └ E
└ C
  ├ F
  └ G
*/
EventHandler<StructureChangedEventArgs<ObservableNamedNode>> structreChangedHdlr = (s, e) => {
    Console.WriteLine($"sender:{s} \nTarget:{e.Target} TreeAction:{e.TreeAction} PreviousParentOfTarget:{e.PreviousParentOfTarget} OldIndex:{e.OldIndex} IsAncestorChanged:{e.IsAncestorChanged} IsDescendantChanged:{e.IsDescendantChanged}");
    if (e.IsAncestorChanged) {
        var info = e.AncestorInfo!;
        Console.WriteLine($"MovedTarget:{info.MovedTarget} OldIndex:{info.OldIndex} PreviousParentOfTarget:{info.PreviousParentOfTarget} IsRootChanged:{info.IsRootChanged}");
    }
    if (e.IsDescendantChanged) {
        var info = e.DescendantInfo!;
        Console.WriteLine($"Target:{info.Target} SubtreeAction:{info.SubTreeAction} OldIndex:{info.OldIndex} PreviousParentOfTarget:{info.PreviousParentOfTarget}");
    }
    Console.Write("\n");
};

PropertyChangedEventHandler propertyChangedHdlr = (s, e) => {
    if(e.PropertyName == "Parent")
        Console.WriteLine($"sender:{s} Parent Changed.\n");
};

foreach (var node in root.PreOrder()) {
    node.StructureChanged += structreChangedHdlr;
    node.PropertyChanged += propertyChangedHdlr;
}

Notifications When a Node Is Removed

Console.WriteLine("Remove node D");
nodesDic["B"].RemoveChild(nodesDic["D"]);
Console.WriteLine(root.ToTreeDiagram(x => x.Name));

alt text
alt text

Nodes A and B, nodes C, E, F, and G, and nodes D, H, and I each receive the same notification content within their respective groups.

Nodes A and B have IsDescendantChanged set to true, and their DescendantInfo is displayed. Nodes C, E, F, and G are neither ancestors nor descendants of the changed node D, so both IsAncestorChanged and IsDescendantChanged are false. The detached nodes D, H, and I have IsAncestorChanged set to true, and their AncestorInfo is displayed.

Notifications When a Node Is Added

Console.WriteLine("Add node D as a child node to node E.");
nodesDic["E"].AddChild(nodesDic["D"]);
Console.WriteLine(root.ToTreeDiagram(x => x.Name));

alt text
alt text

Nodes A, B, and E have changes in their descendants, so IsDescendantChanged is true. Nodes C, F, and G have both flags set to false. Nodes D, H, and I have changes in their ancestors, so IsAncestorChanged is true.

Notifications When a Node Is Moved

Console.WriteLine("Move node E to be a child node of node C.");
nodesDic["C"].AddChild(nodesDic["E"]);
Console.WriteLine(root.ToTreeDiagram(x => x.Name));

alt text
alt text
From the perspective of the entire tree (node A), node E moved within the tree, so TreeAction is Move. From the perspective of node B, node E left its subtree, so SubTreeAction is Leave. From the perspective of node C, node E entered its subtree from outside, so SubTreeAction is Join.

Because the move occurred within the tree, IsRootChanged is false from the perspective of nodes E, D, H, and I.

NAryTreeNode

The number of elements in the child node collection is fixed to the value specified during initialization or in the constructor.

public class CustomNaryTreeNode : NAryTreeNode<CustomNaryTreeNode> {
	public CustomNaryTreeNode(int nary) : base(nary) { }
	public CustomNaryTreeNode() : base(2) { }
	public string Name { get; set; }
}

By default, an array is used as the internal collection. protected override IEnumerable<TNode> SetupChildCollection() => new List<TNode>();
This initializes the child node collection as a list.

There are two points to note when using a fixed number of elements:

  • The length of the child node collection does not change when nodes are added or removed.
  • Elements whose value is null are not included in enumeration.

Empty slots are initialized to null by default. When a child is added, it is placed in a null slot; when a child is removed, its slot is set back to null. If there are no null slots, an attempt to add a child using AddChild will fail. Use TryAddChild if you need to obtain the result indicating whether the child was added successfully.

The following example attempts to assemble a ternary tree using nodes with two child slots.

var lst = "ABCDEFGH".ToCharArray().Select(x => new CustomNaryTreeNode(2) { Name = x.ToString()});
var root = lst.AssembleAsNAryTree(3);
Console.WriteLine(root.ToTreeDiagram(x => $"{x.Name}, BranchIndex: {x.BranchIndex()}"));
/*
A, BranchIndex: -1
├ B, BranchIndex: 0
│ ├ E, BranchIndex: 0
│ └ F, BranchIndex: 1
└ C, BranchIndex: 1
  └ H, BranchIndex: 0
*/

The third child cannot be added, so nodes D and G are not included. The following code removes node B.

root.RemoveAllChild(x=>x.Name == "B");
Console.WriteLine(root.ToTreeDiagram(x => $"{x.Name}, BranchIndex: {x.BranchIndex()}"));
Console.WriteLine("In-Order:" + string.Join(",", root.InOrder().Select(x=>x.Name)));
/*
A, BranchIndex: -1
└ C, BranchIndex: 1
  └ H, BranchIndex: 0

In-Order:A,H,C
*/

Even after node B is removed, the index of node C remains 1.

When converting to an NAryTree with the Convert method or assembling an NaryTree with the AssembleTree method, you must also specify the child index.

var dic = root.ToNodeMap(x=>x.Name);
foreach(var pair in dic) 
    Console.WriteLine($"key:{pair.Key}, value:{pair.Value}");
/*
key:[], value:A
key:[1], value:C
key:[1,0], value:H
*/

var root1 = dic.AssembleTree(
    x => new CustomNaryTreeNode(2) { Name = x.ToString() }, 
    (p, c, i) => p.SetChild(i, c));
Console.WriteLine(root1.ToTreeDiagram(x => $"{x.Name}, BranchIndex: {x.BranchIndex()}"));
Console.WriteLine("In-Order:" + string.Join(",", root1.InOrder().Select(x=>x.Name)));
/*
A, BranchIndex: -1
└ C, BranchIndex: 1
  └ H, BranchIndex: 0

In-Order:A,H,C
*/

For comparison, the following examples show the results when no index is specified and when the tree is converted to a GeneralTree.

var root2 = dic.AssembleTree(x => new CustomNaryTreeNode(2) { Name = x});
Console.WriteLine(root2.ToTreeDiagram(x => $"{x.Name}, BranchIndex: {x.BranchIndex()}"));
Console.WriteLine("In-Order:" + string.Join(",", root2.InOrder().Select(x=>x.Name)));
/*
A, BranchIndex: -1
└ C, BranchIndex: 0
  └ H, BranchIndex: 0

In-Order:H,C,A
*/

// NAry tree -> General tree
var root3 = root.Convert(x => new NamedNode() { Name = x.Name });
Console.WriteLine(root3.ToTreeDiagram(x => $"{x.Name}, BranchIndex: {x.BranchIndex()}"));
Console.WriteLine("In-Order:" + string.Join(",", root3.InOrder().Select(x=>x.Name)));
/*
A, BranchIndex: -1
└ C, BranchIndex: 0
  └ H, BranchIndex: 0

In-Order:H,C,A
*/

If no index is specified, child nodes are added sequentially from the first slot, so the original BranchIndex values cannot be reproduced. A GeneralTree cannot represent a state in which the element at index 0 is null.

Enumerating and Displaying null Values

As mentioned above, null values are not included in enumeration by default, but there are ways to display or enumerate them. The following example uses this tree:

var root = new Dictionary<NodeIndex, CustomNaryTreeNode>() {
    [new NodeIndex()] = new CustomNaryTreeNode(3) { Name = "A" },
    [new NodeIndex(0)] = new CustomNaryTreeNode(2) { Name = "B" },
    [new NodeIndex(1)] = new CustomNaryTreeNode(2) { Name = "C" },
    [new NodeIndex(0, 1)] = new CustomNaryTreeNode(0) { Name = "D" },
    [new NodeIndex(1, 1)] = new CustomNaryTreeNode(2) { Name = "E" },
}.AssembleTree((p, c, i) => p.SetChild(i, c));

Console.WriteLine(root.ToTreeDiagram(x => $"{x.Name} branchIndex:{x.BranchIndex()}"));
/*
A branchIndex:-1
├ B branchIndex:0
│ └ D branchIndex:1
└ C branchIndex:1
  └ E branchIndex:1
*/

To display null slots, specify the text to display for them in an argument of the ToTreeDiagram method.

Console.WriteLine(root.ToTreeDiagram(x => x.Name,"empty"));
/*
A
├ B
│ ├ empty
│ └ D
├ C
│ ├ empty
│ └ E
│   ├ empty
│   └ empty
└ empty
*/

To include null slots in enumeration, use ReadOnlyValuedTreeNode.

Console.WriteLine(root.AsValuedTreeNode(x => x).ToTreeDiagram(x => x.Value?.Name ?? "null"));
/*
A
├ B
│ ├ null
│ └ D
├ C
│ ├ null
│ └ E
│   ├ null
│   └ null
└ null
*/
Console.WriteLine($"InOrder(do not ignore null): {string.Join(',', root.AsValuedTreeNode(x => x).InOrder().Select(x => x.Value?.Name ?? "null"))}");
Console.WriteLine($"InOrder(ignore null)       : {string.Join(',', root.InOrder().Select(x => x.Name))}");
/*
InOrder(do not ignore null): null,B,D,A,null,C,null,E,null,null
InOrder(ignore null)       : B,D,A,C,E
*/

Dispose Behavior

If a derived class needs to perform disposal operations, use protected virtual void Dispose(bool disposing). The node being disposed and all of its descendants are disposed.

public class DisposableNode 
    : ObservableGeneralTreeNode<DisposableNode>, IDisposable {

	public string Name { get; set; }

	public override string ToString() => this.Name;

	private bool disposedValue;
	protected override void Dispose(bool disposing) {
		if (disposedValue) return;
		if (disposing) {
			Console.WriteLine($"Start disposing {this.Name}.");
		}
		base.Dispose(disposing);
		Console.WriteLine($"Finished disposing {this.Name}.");
		disposedValue = true;
	}
	public void Dispose() {
		Dispose(disposing: true);
		GC.SuppressFinalize(this);
	}
}

The following code demonstrates the disposal process.

var nodesDic = "ABCD".ToCharArray().Select(x => x.ToString()).ToDictionary(x => x, x => new DisposableNode() { Name = x });
var root = nodesDic.Values.AssembleAsNAryTree(1);

EventHandler<StructureChangedEventArgs<DisposableNode>> structreChangedHdlr = (s, e) => {
    if (s == e.Target && e.IsAncestorChanged) {
        Console.WriteLine($"sender:{e.Target} ,TreeAction:{e.TreeAction}");
    }
};
foreach (var node in root.PreOrder()) {
    node.StructureChanged += structreChangedHdlr;
}
Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
└ B
  └ C
    └ D
*/

nodesDic["B"].Dispose();
/*
Start disposing B.
Start disposing D.
sender:D ,TreeAction:Leave
Finished disposing D.
Start disposing C.
sender:C ,TreeAction:Leave
Finished disposing C.
sender:B ,TreeAction:Leave
Finished disposing B.
*/

Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
*/

When node B is disposed, its descendants are disposed and detached, starting from the deepest nodes.

  • Node B: disposal starts
    • Node D: disposal starts
    • Node D: detached from its parent
    • Node D: disposal completes
    • Node C: disposal starts
    • Node C: detached from its parent
    • Node C: disposal completes
  • Node B: detached from its parent
  • Node B: disposal completes
Process Scope Order
Disposal starts Target and descendants (reverse level order) B, D, C
Detachment Descendants (reverse level order), then target D, C, B
Disposal completes Descendants (reverse level order), then target D, C, B

The order in which Dispose is called is B, D, C (the node on which Dispose was called directly, followed by descendants in reverse level order). The detachment order is D, C, B (reverse level order). The order in which disposal completes is also D, C, B.

If a derived class implements IDisposable, the tree may contain descendants that do not implement IDisposable. When an ancestor node is disposed in this situation, descendants that do not implement IDisposable are only detached.

public class DspObsNamedNode : ObservableNamedNode, IDisposable {
	private bool disposedValue;
	protected override void Dispose(bool disposing) {
		if (disposedValue) return;
		if (disposing) {
			Console.WriteLine($"Start disposing {this.Name}.");
		}
		base.Dispose(disposing);
		Console.WriteLine($"Finished disposing {this.Name}.");
		disposedValue = true;
	}
	public void Dispose() {
		Dispose(disposing: true);
		GC.SuppressFinalize(this);
	}
}
var dic = new List<ObservableNamedNode>() {
	new DspObsNamedNode(){ Name = "A" },
	new DspObsNamedNode(){ Name = "B" },
	new ObservableNamedNode(){ Name = "C" },
	new ObservableNamedNode(){ Name = "D" },
	new DspObsNamedNode(){ Name = "E" },
}.ToDictionary(x => x.Name, x => x);

var root = dic.Values.AssembleAsNAryTree(1);

EventHandler<StructureChangedEventArgs<ObservableNamedNode>> structreChangedHdlr = (s, e) => {
	if (s == e.Target && e.IsAncestorChanged) {
		Console.WriteLine($"sender:{e.Target} ,TreeAction:{e.TreeAction}");
	}
};
foreach (var node in root.PreOrder()) {
	node.StructureChanged += structreChangedHdlr;
}
Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
└ B
  └ C
    └ D
      └ E
*/
(dic["B"] as DspObsNamedNode)?.Dispose();
/*
Start disposing B.
Start disposing E.
sender:E ,TreeAction:Leave
Finished disposing E.
sender:D ,TreeAction:Leave
sender:C ,TreeAction:Leave
sender:B ,TreeAction:Leave
Finished disposing B.
*/

Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
*/

Clone this wiki locally