c类继承自泛型,方法返回类型
本文关键字:方法 返回类型 泛型 继承 | 更新日期: 2023-09-27 18:22:37
我有一个应该是树的泛型类,我想继承这样的类:
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);
}
问题是为什么以及如何修复它?
编辑:我创建了控制台程序,运行它,它就可以工作了。所以这一定是我的发动机出了问题!
public ComboTree(IComboAction action)
: base(action)
{
Movement = null; // <---- You are nulling Movement in the second constructor
}