我有一个应该是树的泛型类,我想继承这样的类:
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时,我总是得到null。我知道类型转换存在问题,但是为什么如果ComboTree继承Tree?
void readMove(IComboAction action) {
ComboTree leaf = (ComboTree)currentLeaf.findInLeaves(action);
}
问题是为什么以及如何解决它?
编辑:我创建了控制台程序,运行它并且它可以运行。所以这一定是我的引擎问题!
答案 0 :(得分:0)
public ComboTree(IComboAction action)
: base(action)
{
Movement = null; // <---- You are nulling Movement in the second constructor
}