【发布时间】:2012-07-22 00:12:48
【问题描述】:
所以我正在尝试创建一个返回数据列表的函数,数据有许多“子”类,其中一个是 Comment,但是,如果日期类型是 Comment(我用 IF 语句测试),那么我想按编辑日期排序,而不是按 id 排序(ID 可用于所有数据对象,而编辑日期仅可用于 cmets 类)。因此,我没有做 TypeOf,而是做 TypeOf,然后我可以在编辑日期订购它,但是它想返回一个列表,但我需要它是一个列表,但是我已经用谷歌搜索了一个小时 + 并没有找到运气关于如何转换它。方法如下:
private List<T> GetAllData<T>() where T : Data, new()
{
List<T> TmpList = new List<T>();
if (typeof(T) == typeof(Comment))
{
TmpList = _newdb.Data.OfType<Comment>().OrderBy(x => x.EditDate).ToList();
// THIS ABOVE doesn t work ofc since it wants to return a List<Comment> but TmpList is a List<T>
//List<Comment> TmpComments = _newdb.Data.OfType<Comment>().OrderBy(x => x.EditDate).ToList();
// List<T> tempzor = new List<T>(TmpComments.ToList());
//TmpList = (List<T>(TmpComments));
// TmpList = TmpComments.ConvertAll;
}
else
{
TmpList = _newdb.Data.OfType<T>().OrderBy(x => (x.Id)).ToList();
}
return TmpList;
}
提前致谢!
【问题讨论】:
-
看来你需要在某个地方打电话给
.Cast<Comment>() -
当您调用
GetAllData<Comment>()时,返回List<T>将是List<Comment>。
标签: c# list function inheritance