我与一位 friend 讨论了集合在方法的返回/输入值中的用法。他告诉我我们必须使用 - 返回值的最派生类型。 - 输入参数的最少派生类型。
因此,这意味着,例如,一个方法必须获取一个 ReadOnlyCollection 作为参数,并返回一个列表。
此外,他说我们不能在公共(public) API 中使用 List 或 Dictionary,我们必须使用 Collection,ReadOnlyCollection,...... 所以,在方法是公共(public)的情况下,它的参数和它的返回值必须是 Collection、ReadOnlyCollection、...
对吗?
请您参考如下方法:
关于输入参数,通常使用最不具体的类型更灵活。例如,如果您的方法要做的只是枚举作为参数传递的集合中的项目,那么接受 IEnumerable
例如,考虑一个接受客户集合参数的方法“ProcessCustomers”:
public void ProcessCustomers(IEnumerable<Customer> customers)
{
... implementation ...
}
如果您将参数声明为 IEnumerable
private IEnumerable<Customer> GetCustomersByCountryCode(IEnumerable<Customer> customers, int countryCode)
{
foreach(Customer c in customers)
{
if (c.CountryCode == countryCode) yield return c;
}
}
...
ProcessCustomers(GetCustomersByCountryCode(myCustomers, myCountryCode);
...
一般 MS 指南建议不要公开 List
