C# - 使用CRTP的侵入式树结构

s0u*_*bap 5 c# tree crtp

我目前正在研究一种在C#中实现侵入式树结构的简单方法.因为我主要是C++程序员,所以我立即想要使用CRTP.这是我的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

这工作但是...我无法理解为什么我必须在调用a_node.SetParent((T)this时)进行转换,因为我使用泛型类型限制... C#cast有成本,我想要不要在每个侵入式集合实现中传播这个演员......

usr*_*usr 3

这至少是 TreeNode 类型。它可以是派生的,也可以是 TreeNode。SetParent 需要一个 T。但 T 可以是与此不同的类型。我们知道 this 和 T 都派生自 TreeNode 但它们可以是不同的类型。

例子:

class A : TreeNode<A> { }
new TreeNode<A>() //'this' is of type 'TreeNode<A>' but required is type 'A'
Run Code Online (Sandbox Code Playgroud)