可以在父类中指定基类中的泛型

时间:2012-05-09 20:49:14

标签: c# generics

我有一个基类,它有在C#中使用泛型类型的方法,然后我有其他继承这些类的类,我想在父类中指定类型以避免在任何地方使用尖括号......

这是我的基类类CBaseHome

中的示例方法
public List<T> fetchAll<T>(CBaseDb db, bool includeEmpty = true) where T : CBaseTable, new()
{
    List<T> retVal = new List<T>();
    ...
    return retVal;
}

我有一个继承自这个类的父类(不覆盖这个函数)

在那个消耗它的类中,我有以下代码......

List<student> students = new limxpoDB.Home.student().fetchAll<student>(db, false);

所以这里的Home.student类继承了CBaseHome类,学生继承了CBaseTable ......

我希望能够在Home.student类中说,该类唯一有效的泛型类型是学生,以便我的消费代码看起来像......

List<student> students = new limxpoDB.Home.student().fetchAll(db, false);

我在这里意识到差异很小,但我也在一些VB&gt;网络代码中使用这个库,它看起来很糟糕......

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:4)

子类不能强加方法上的泛型类型参数。如果我有:

public class Parent {
    public List<T> GetStuff<T>() { ... }
}

我做不到:

public class Child : Parent {
    // This is not legal, and there is no legal equivalent.
    public List<ChildStuff> GetStuff<ChildStuff>() { ... }
}

你可以做的是让父是通用的,而不是它的方法:

public class Parent<T> {
    public List<T> GetStuff() { ... }
}

public class Child : Parent<ChildStuff> {
    // GetStuff for Child now automatically returns List<ChildStuff>
}
相关问题