我有一个基类,它具有在 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类,而student继承了CBaseTable...
我希望能够在 Home.student 类中声明该类唯一有效的泛型类型是学生,这样我的消费代码看起来就像...
List<student> students = new limxpoDB.Home.student().fetchAll(db, false);
我意识到区别很小,但我也在一些 VB>Net 代码中使用了这个库,它看起来很糟糕......
有什么想法吗?
谢谢
请您参考如下方法:
方法的通用类型参数不能由子类强加。所以如果我有:
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>
}
