简体   繁体   中英

c# class inherits from generics, method return type

I have generic class that should be a tree and I want to inherit the class like this:

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;
        }
    }
}

Putting data works well, but when I try to use method findInLeaves I always get null. I understand there is a problem with type casting, but why if ComboTree inherits Tree?

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

Question is why and how to fix it?

Edit: I created console program, run it and it works. So this must be my engine problem!

public ComboTree(IComboAction action)
    : base(action)
{
    Movement = null; // <---- You are nulling Movement in the second constructor
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM