why casting Base object to derived type reference working?

99封情书 提交于 2019-12-13 04:38:52

问题


AFAIK, casting a base class object to derived type reference throws a run time exception.But in the below class, this works perfectly fine.

public class Node<T>
{
        // Private member-variables
        private T data;
        private NodeList<T> neighbors = null;

        public Node() {}
        public Node(T data) : this(data, null) {}
        public Node(T data, NodeList<T> neighbors)
        {
            this.data = data;
            this.neighbors = neighbors;
        }

        public T Value
        {
            get
            {
                return data;
            }
            set
            {
                data = value;
            }
        }

        protected NodeList<T> Neighbors
        {
            get
            {
                return neighbors;
            }
            set
            {
                neighbors = value;
            }
        }
    }
}   

public class BinaryTreeNode<T> : Node<T>
{
    public BinaryTreeNode() : base() {}
    public BinaryTreeNode(T data) : base(data, null) {}
    public BinaryTreeNode(T data, BinaryTreeNode<T> left, BinaryTreeNode<T> right)
    {
        base.Value = data;
        NodeList<T> children = new NodeList<T>(2);
        children[0] = left;
        children[1] = right;

    base.Neighbors = children;
}

public BinaryTreeNode<T> Left
{
    get
    {
        if (base.Neighbors == null)
            return null;
        else
            return (BinaryTreeNode<T>) base.Neighbors[0];
    }
    set
    {
        if (base.Neighbors == null)
            base.Neighbors = new NodeList<T>(2);

        base.Neighbors[0] = value;
    }
}

This is the code taken from one of the sample from MSDN - http://msdn.microsoft.com/en-us/library/ms379572(v=vs.80).aspx

as per my understanding, In property Left

(BinaryTreeNode<T>) base.Neighbors[0]

casts the (base) Node to (derived) BinartTreeNode. How is this working ?


回答1:


Precisely because it works, we can conclude that the object in question is actually a BinaryTreeNode<T> (or a subclass of that). Objects never change type once created, so somewhere (not shown in your example) you are creating a BinaryTreeNode<T>, storing it as the neighbor (where all we know is that it is a Node<T> - which is fine: it is true to say that any BinaryTreeNode<T> is a Node<T>; class inheritance means "is a"), and then successfully casting it back again. That is legal, but will fail at runtime if the node turns out to not be a BinaryTreeNode<T>.



来源:https://stackoverflow.com/questions/22686352/why-casting-base-object-to-derived-type-reference-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!