如何从基类泛型类派生泛型类?

时间:2015-09-28 13:58:56

标签: c# generics inheritance

我有一个基本抽象泛型类

public abstract class A<T> where T: Control
{
    protected T _t { get; set; }

    protected abstract void Method ();

    protected A(T t)
    {
        _t = t;
    }
}

B类派生自A类型TreeView

public class B<T>: A<TreeView>
{
    protected override void Method ()
    {
        _t.CallSomeTreeViewMethod (); // ok!
    }

    public B (TreeView tree): base (tree)
    {

    }
} 

如何从具有派生自TreeView的类型的B类派生?

public class C: B<ExtendedTreeView>
{
    protected override void Method ()
    {
        _t.CallSomeExtendedTreeViewMethod ();
    }

    public C (ExtendedTreeView tree): base (tree)
    {

    }
}

1 个答案:

答案 0 :(得分:4)

而不是具体的类TreeView添加一个通用约束:

public class B<T>: A<T> where T:TreeView
{
    protected override void Method ()
    {
        _t.CallSomeTreeViewMethod (); // ok!
    }

    public B (T tree): base (tree)
    {

    }
}