How to create a complete treeview general data structure

I want to create a fully generic tree, similar to a structure. something like that:

public class TreeView<T, K, L> { public T source; public K parent; public List<L> children; } 

as you can see in this source class, the parent as well as the child, all have a different common data type. I also want my tree to have an unlimited number of levels (not only 3). that way, when I want to work with my nodes in code, they will all be strongly typed. not just the objects that I need to convert to their original type.

Is it possible to create such a structure in C #, a tree structure, which all its nodes are heavily typed?

thanks

+7
generics c # treeview strong-typing
source share
3 answers

This is a big problem with tree data structures. It is easy to identify homogeneous trees, but in the real world trees often consist of heterogeneous types of objects. A good example of this is a file system in which a tree contains disks, folders, and files.

You can only create a safe type tree if you know the exact shape of the tree at compile time. Of course, this eliminates every real use case for trees.

+2
source share

Well, besides the tree, you will have some basic data. For example, a directory tree. Directory attributes are its name and a list of child directories. Let's start by defining a common TreeItem .

 public class TreeItem<T> { public TreeItem() { Children = new List<TreeItem<T>>(); } public void AddChild(T data) { Children.Add(new TreeItem<T>{Data = data, Parent = this}); } public List<TreeItem<T>> Children{get;set;} public TreeItem<T> Parent {get;set;} public T Data {get;set;} } 

So, a simple directory tree is just a TreeItem<string> :

 var directories = new TreeItem<string> { Data="root" }; directories.AddChild("child1"); directories.AddChild("child2"); directories.AddChild("child3"); 

This will create a tree like this:

 root |- child1 |- child2 |- child3 

The only way to create a fully general tree view is to have the same types for the current node, node above and all child nodes, otherwise you must fix the structure at compile time and only support a set of hierarchies.

+2
source share

After reading the Igors, respond and your comment and you can simply say that this is impossible. All you can do is use T some basic type that all classes have, like a base class or an interface.

But if you need to specify a specific type somewhere in your code that you will need to use, which can lead to some if-return or if-else-if structure, for example:

 SpecificType specType = commonType as SpecificType; if(specType != null) { //Do something... return; } AnotherSpecifcType specType2 = commonType as AnotherSpecifcType; if(specType2 != null) { //Do something... return; } 

But that’s all you can do.

+1
source share

All Articles