【发布时间】:2014-11-27 12:38:08
【问题描述】:
我有一个集合类,比如说UserCollection,它派生自Collection(通用集合的基类)。
现在我想要一个UserCollection,这是我的代码,但它不能从通用List 转换为我的集合类:
public class User
{
// All user Fields
}
public class UserCollection : Collection<User>
{
public static UserCollection GetUserCollection()
{
DataTable table = ...//all users data from DB
List<User> userList = table.ToCollection<User>(); // Call an extension method to convert to generic List of user
return userList; // Cannot implicitly convert type 'System.Collections.Generic.List<User>' to 'UserCollection'
}
}
// ToCollection 函数在这里
http://www.codeproject.com/Tips/195889/Convert-Datatable-to-Collection-using-Generic
我需要什么才能让它工作?
【问题讨论】:
-
您必须再次循环列表并将
Add每个用户一个接一个地循环到UserCollection。 -
@Tim,所以从 Collection 派生并没有给我任何额外的好处,除了提供添加/删除等功能?
-
你为什么要创建一个新的自定义类而不是使用
List<T>?
标签: c# generics collections