开发者

type hierarchy with type parameters?

imagine this layout of classes i use for building a tree structure:

class Treenodebase
{
    Treenodebase Parent{get;set;}
    IEnumerable<Treenodebase> Children {get;set;}
}
class Specialtreenode : Treenodebase
{
    string SpecialProperty{get;set;}
    public string ParentsSpecialProperty()
    {
        return Parent.SpecialProperty; //here I'd need casting?!
    }
}
class Othertreenode : Treenodebase
{
    string OtherProperty {get;set;}
}

I use the subclasses to bui开发者_如何学编程ld seperate trees throughout my program. that means each Specialtreenode only ever has a parent of type Specialtreenode, and also children of type Specialtreenode.

The snipped is very simplified. The base class has many more properties (like IsSelected and IsExpanded) and methods (think 'Ancestors' or 'Siblings' and the like) and the subclasses too.

Can I somehow utilize type parameters here to avoid casting within each of the subclasses? Or would that always involve my subclasses not inheriting from the baseclass?


You could do something like this:

class Treenodebase<T> where T : Treenodebase<T>
{
    public T Parent{get;set;}
    public IEnumerable<T> Children {get;set;}
}
class Specialtreenode : Treenodebase<Specialtreenode>
{
    string SpecialProperty{get;set;}
    public string ParentsSpecialProperty()
    {
        return Parent.SpecialProperty;
    }
}

Of course, this eliminates the non-generic Treenodebase type, which could be good or bad. If you have a lot of utility methods that don't really care what implementation you use, you might want to make Treenodebase<T> either extend a non-generic base class or implement a non-generic interface. On the other hand, you might find it easier to just make all your utility methods be generically typed as well. It depends on how you're using the tree in code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜