简体   繁体   中英

C# defining Automatic Properties in Generic Class

I'm new in C# and I am completing the book "Microsoft Visual C# 2013 Step by Step" written by John Sharp. An exercise, regarding "Generics", I found this code:

public class Tree<TItem> where TItem : IComparable<TItem>
{
    public TItem NodeData { get; set; }
    public Tree<TItem> LeftTree { get; set; }
    public Tree<TItem> RightTree { get; set; }

    public Tree(TItem nodeValue)
    {
        this.NodeData = nodeValue;
        this.LeftTree = null;
        this.RightTree = null;
    }

    public void Insert(TItem newItem)
    {
        TItem currentNodeValue = this.NodeData;
        if (currentNodeValue.CompareTo(newItem) > 0)
        {
            // Insert the new item into the left subtree
            // code here....
        }
        else
        {
            // Insert the new item into the right subtree
            // code here....
        }
    }

}

I can't understand why he defined the properties in different mode. One in this way:

public TItem NodeData { get; set; }

And the others in this:

public Tree<TItem> LeftTree { get; set; }
public Tree<TItem> RightTree { get; set; }

Someone can explain me why? Thank you

These properties are being used for different things. As their name suggest:

  • NodeData is used to facilitate the information stored in the tree.
  • LeftTree / RightTree are there to facilitate the topology of the tree - each current object (node) is basically a root of a tree rooted at itself. So as it is a binary tree it has two direct descendants - the left and the right nodes.

Where the part where the generics come to play is about the what is the kind of data stored in the tree. So the NodeData is trivially of "type" TItem . The left and right nodes are of type Tree<TItem> so to ensure that at any depth of the tree it is a TItem type of data that is stored.

To make it simpler lets suppose that you wanted to create a binary tree of integers. Then you'd model it by:

public class Tree 
{
    public int Data { get; set; }
    public Tree Left {get; set; }
    public Tree Right {get; set; }
}

I think this way you can really see what is the fundamental difference between the Data and Left , Right properties.

He defines a tree. The NodeData property is the current node value. Then if the value is smaller than the the current node, the new value is put on the left, otherwise on the right. If the type of LeftValue and RightValue are Tree, it's to have a parent-child structure. This class allows to create a data structure like binary tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM