, , 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 .