0

我有应该是一棵树的通用类,我想像这样继承该类:

public class Tree<T> {
    private HashSet<Tree<T>> leaves;
    private T data;

    public Tree() {
        leaves = new HashSet<Tree<T>>();
    }

    public Tree(T data) : this() {
        this.data = data;
    }

    public T Data {
        get {
            return this.data;
        }
        set {
            data = value;
        }
    }

    public virtual Tree<T> findInLeaves(T data) {
        foreach(Tree<T> leaf in leaves) {
            if(leaf.Data.Equals(data)) {
                return leaf;
            }
        }
        return null;
    }
}

public class ComboTree : Tree<IComboAction> {
    private ComboMovement movement;

    public ComboTree() : base() {
        Movement = null;
    }

    public ComboTree(IComboAction action) : base(action) {
        Movement = null;
    }

    public ComboMovement Movement {
        get {
            return this.movement;
        }
        set {
            movement = value;
        }
    }
}

放置数据效果很好,但是当我尝试使用方法 findInLeaves 时,我总是得到空值。我知道类型转换存在问题,但是为什么 ComboTree 继承了 Tree?

void readMove(IComboAction action) {
    ComboTree leaf = (ComboTree)currentLeaf.findInLeaves(action);
}

问题是为什么以及如何解决它?

编辑:我创建了控制台程序,运行它并且它可以工作。所以这一定是我的引擎问题!

4

1 回答 1

0
public ComboTree(IComboAction action)
    : base(action)
{
    Movement = null; // <---- You are nulling Movement in the second constructor
}
于 2013-07-16T10:02:54.057 回答