C # - Intrusive Tree Structure Using CRTP

I'm currently working on a simple way to implement an intrusive tree structure in C #. Since I am mainly a C ++ programmer, I immediately wanted to use CRTP. Here is my code:

public class TreeNode<T> where T : TreeNode<T>
{
    public void AddChild(T a_node)
    {
        a_node.SetParent((T)this); // This is the part I hate
    }

    void SetParent(T a_parent)
    {
        m_parent = a_parent;
    }

    T m_parent;
}

This works, but ... I can’t understand why I should use a_node.SetParent ((T) this) when calling, since I use a generic type constraint ... C # cast has a cost and I would not want to distribute this bringing in every intrusive collection implementation ...

+5
source share
5 answers

, , TreeNode. TreeNode. SetParent T. T , . , T TreeNode, .

:

class A : TreeNode<A> { }
new TreeNode<A>() //'this' is of type 'TreeNode<A>' but required is type 'A'
+3

, T this . TreeNode.

, T , .

StupidNode:TreeNode<OtherNode>.

0

:

 TreeNode<T> where T : TreeNode<T>

T, TreeNode, , . , node (.. node node.)

 public class TreeNode<TPayload>
 {
     TPayload NodeStateInfo{get;set;}

     public void AddChild(TreeNode<TPayload> a_node)
     {
         a_node.SetParent(this); // This is the part I hate
     }

     void SetParent(TreeNode<TPayload> a_parent)
     {
     }
 }

, a_node.SetParent(). , AddChild SetParent, a_node. , - , , .

0

, , CRTP, ...

public class Foo : TreeNode<Foo>
{
}

public class Bar : TreeNode<Foo> // parting from convention
{
}

... :

var foo = new Foo();
var foobar = new Bar();
foobar.AddChild(foo);

AddChild InvalidCastException, Unable to cast object of type 'Bar' to type 'Foo'.

CRTP - , , , . , CRTP . , crtp #.

, ...

public class TreeNode<T> where T : TreeNode<T>
{
    public void AddChild(T a_node)
    {
        a_node.SetParent(this);
    }

    void SetParent(TreeNode<T> a_parent)
    {
        m_parent = a_parent;
    }

    TreeNode<T> m_parent;
}

... , InvalidCastException. m_Parent TreeNode<T>; this T Foo class, TreeNode<T> Bar, Bar TreeNode<Foo> - SetParent , . T , , CRTP.

/ /, , " "; , , , , . , , , generics .

0

, , ( ), - . , ?

, AddChild CIL/MSIL. :

ldarg.1
ldarg.0
stfld TreeNode<class T>::m_parent
ret

.NET , . , , , .

IL Visual Studio (, vsix ) # extern MethodImpl.ForwardRef. .il , .

, SetParent AddChild.

0

All Articles