Base class constraint on generic class specifying the class itself

后端 未结 3 1752
南旧
南旧 2021-01-17 15:54

Yesterday, I was explaining C#\'s generic constraints to my friends. When demonstrating the where T : CLASSNAME constraint, I whipped up something like this:

3条回答
  •  终归单人心
    2021-01-17 16:36

    This approach is widely used in Trees and other Graph-like structures. Here you say to compiler, that T has API of UnusableClass. That said, you can implement TreeNode as follows:

    public class TreeNode
        where T:TreeNode
    {
        public T This { get { return this as T;} }
    
        public T Parent { get; set; }
    
        public List Childrens { get; set; }
    
        public virtual void AddChild(T child)
        {
            Childrens.Add(child);
            child.Parent = This;
        }
    
        public virtual void SetParent(T parent)
        {
            parent.Childrens.Add(This);
            Parent = parent;
        }
    }
    

    And then use it like this:

    public class BinaryTree:TreeNode
    {
    }
    

提交回复
热议问题