C#泛型 - 为什么在以这种方式处理类型参数时需要显式转换?

时间:2011-10-13 22:21:22

标签: c# generics

再次,我。对此抱歉。

previous question开始(我认为我未能充分证明我的困惑的根源),这是我写的实际功能:

/// <summary>
///     A b-tree node.
/// </summary>
public class BTreeNode
{
    /// <summary>
    ///     Create a new b-tree node.
    /// </summary>
    public BTreeNode()
    {

    }

    /// <summary>
    ///     The node name.
    /// </summary>
    public string Name
    {
        get;
        set;
    }

    /// <summary>
    ///     The left-hand child node.
    /// </summary>
    public BTreeNode Left
    {
        get;
        set;
    }

    /// <summary>
    ///     The right-hand child node.
    /// </summary>
    public BTreeNode Right
    {
        get;
        set;
    }
}

/// <summary>
///     Perform a breadth-first traversal of a b-tree.
/// </summary>
/// <param name="rootNode">
///     The b-tree's root node.
/// </param>
/// <param name="forEachNode">
///     An action delegate to be called once for each node as it is traversed.
///     Also includes the node depth (0-based).
/// </param>
public static void TraverseBreadthFirst<TNode>(this TNode rootNode, Action<TNode, int> forEachNode)
    where TNode : BTreeNode
{
    if (rootNode == null)
        throw new ArgumentNullException("rootNode");

    if (forEachNode == null)
        throw new ArgumentNullException("forEachNode");

    Queue<Tuple<TNode, int>> nodeQueue = new Queue<Tuple<TNode, int>>(3); // Pretty sure there are never more than 3 nodes in the queue.

    nodeQueue.Enqueue(new Tuple<TNode, int>(rootNode, 0));
    while (nodeQueue.Count > 0)
    {
        Tuple<TNode, int> parentNodeWithDepth = nodeQueue.Dequeue();
        TNode parentNode = parentNodeWithDepth.Item1;
        int nodeDepth = parentNodeWithDepth.Item2;

        forEachNode(parentNode, nodeDepth);
        nodeDepth++;

        if (parentNode.Left != null)
            nodeQueue.Enqueue(new Tuple<TNode, int>((TNode)parentNode.Left, nodeDepth));

        if (parentNode.Right != null)
            nodeQueue.Enqueue(new Tuple<TNode, int>((TNode)parentNode.Right, nodeDepth));
    }
}

我不确定为什么在这里需要显式转换为TNode:

nodeQueue.Enqueue(new Tuple<TNode, int>((TNode)parentNode.Left, nodeDepth));

在什么情况下,parentNode.Left可能无法分配给TNode(因为TNode被限制为BTreeNode类型或派生类型。)

以另一种方式提出问题,在什么情况下此函数会导致InvalidCastException?如果没有,那么为什么编译器需要显式转换?

编辑:我认为我可以将实现更改为:

TNode leftNode = parentNode.Left as TNode;
Debug.Assert(leftNode != null || parentNode.Left == null, "Left child is more derived.");
if (leftNode != null)
    nodeQueue.Enqueue(new Tuple<TNode, int>(leftNode, nodeDepth));

2 个答案:

答案 0 :(得分:4)

parentNode.Left仅输入BTreeNode。不能保证它与TNode相同。想象一下你有:

class SpecialBTreeNode : BTreeNode
class BoringBTreeNode : BTreeNode

现在考虑TraverseBreadthFirst<SpecialBTreeNode>(rootNode, ...)。什么阻止rootNode.Left返回BoringBTreeNode

// This is entirely valid...
SpecialBTreeNode special = new SpecialBTreeNode();
special.Left = new BoringBTreeNode();

听起来你可能想让BTreeNode本身变得通用:

public class BTreeNode<T> where T : BTreeNode<T>
{
    public T Left { get; set; }
    public T Right { get; set; }
}

答案 1 :(得分:0)

您的parentNode.Left定义为BTreeNode,而不是TNode。即使您派生TNode:BTreeNode,您的.Left仍然是BTreeNode引用,而不是TNode引用。所以你必须施展。正如Jon Skeet指出的那样,你需要BTreeNode类是通用的。