C# 使用泛型集合类获取其他类的集合

C# 使用泛型集合类获取其他类的集合,c#,generics,collections,C#,Generics,Collections,我有一个collection类,比如说UserCollection,它派生自collection(泛型集合的基类) 现在我想要一个UserCollection,这是我的代码,但是它说它不能从genericList转换到我的collection类: public class User { // All user Fields } public class UserCollection : Collection<User> { public static UserCollec

我有一个collection类,比如说
UserCollection
,它派生自
collection
(泛型集合的基类)

现在我想要一个
UserCollection
,这是我的代码,但是它说它不能从generic
List
转换到我的collection类:

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'
   }
}
公共类用户
{
//所有用户字段
}
公共类UserCollection:集合
{
公共静态UserCollection GetUserCollection()
{
DataTable=…//数据库中的所有用户数据
List userList=table.ToCollection();//调用扩展方法以转换为用户的通用列表
return userList;//无法将类型“System.Collections.Generic.List”隐式转换为“UserCollection”
}
}
//这里是ToCollection函数


我需要什么才能使它工作?

您可以提供一个适当的构造函数来调用基本构造函数:

public class UserCollection : Collection<User>
{
    public UserCollection() { }
    public UserCollection(IList<User> users) : base(users) { }

    public static UserCollection GetUserCollection()
    {
        // ...
        List<User> userList = ... 
        return new UserCollection(userList);
    }
}
public类UserCollection:Collection
{
公共UserCollection(){}
公共用户集合(IList用户):基本(用户){}
公共静态UserCollection GetUserCollection()
{
// ...
列表用户列表=。。。
返回新的UserCollection(userList);
}
}
或者您必须返回
ICollection
,因为
List
不是
Collection
UserCollection
的子类,但它实现了
ICollection


这里有一个相关的问题:

这有两个原因不起作用。首先,不能将类强制转换为继承的类。UserCollection是一个集合,但集合不是UserCollection。您可以将UserCollection分配给集合变量,但不能反过来分配。此外,您将从ToCollection方法收到一个列表。您遇到了相同的场景:集合不是列表。有关铸造的详细信息,请参见

一种解决方案是实现一个构造函数,该构造函数调用接受IList的基本构造函数,如下所示:

公共用户集合(IList用户)
:基本(用户)
{
}
然后您可以修改GetUserCollection方法以调用它:

public static UserCollection GetUserCollection()
{
   DataTable table = ...//all users data from DB
   List<User> userList = table.ToCollection<User>(); 
   return new UserCollection(userList);
}
publicstaticusercollection GetUserCollection()
{
DataTable=…//数据库中的所有用户数据
List userList=table.ToCollection();
返回新的UserCollection(userList);
}

您必须再次循环列表,并将每个用户逐个添加到
UserCollection
@Tim,因此从Collection派生除了提供添加/删除等功能外,并没有给我任何其他好处?为什么您要创建一个新的自定义类,而不是使用,比如说,
list
?该死,我被打败了。
public static UserCollection GetUserCollection()
{
   DataTable table = ...//all users data from DB
   List<User> userList = table.ToCollection<User>(); 
   return new UserCollection(userList);
}