关于集合返回类型的问题

Rag*_*hav 5 c# collections

在我的 BL(将是公共 API)中,我使用 ICollection 作为我的 Find 方法中的返回类型,例如:

public static ICollection<Customer> FindCustomers()
{
   Collection<Customer> customers = DAL.GetCustomers();

   return customers;
}
Run Code Online (Sandbox Code Playgroud)

请注意使用 ICollection 而不是 Collection<>。

现在在我的 GUI 中,我需要将结果转换回 Collection,例如:

Collection<Customer> customers = (Collection<Customer>)BL.FindCustomers();
Run Code Online (Sandbox Code Playgroud)

这是因为我需要在返回的列表中使用一些 Collection<> 特定的方法,而 ICollection<> 无法做到这一点。

这是正确的用法吗?或者我应该简单地将返回类型从 Collection<> 改为 ICollection<> 以避免这种转换?

其次,我没有使用 IEnumerable,因为它比 ICollection 更通用,甚至没有像 Count 这样的简单属性。而且我真的没有看到在这里概括返回类型的意义。我错过了什么重要的东西吗?

Hen*_*man 2

使用 ICollection 的全部目的是更通用并隐藏更多信息,这是一件好事。

但如果您需要将其转换回来,它就变得毫无意义,您不妨返回功能更强大的 Collection< > 。