![](/img/trans.png)
[英]C# Error CS0738 when class inherits from interface and with type that inherits from interfce type method
[英]c# class inherits from generics, method return type
我有應該是一棵樹的通用類,我想繼承這樣的類:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.