Skip to main content
 首页 » 编程设计

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

2024年02月23日18mq0036

又是我。对此感到抱歉。

在我的 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)); 

请您参考如下方法:

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; } 
}