Skip to main content
 首页 » 编程设计

c#之参数/返回值(集合)的代码约定是什么

2024年01月22日28lhb25

我与一位 friend 讨论了集合在方法的返回/输入值中的用法。他告诉我我们必须使用 - 返回值的最派生类型。 - 输入参数的最少派生类型。

因此,这意味着,例如,一个方法必须获取一个 ReadOnlyCollection 作为参数,并返回一个列表。

此外,他说我们不能在公共(public) API 中使用 List 或 Dictionary,我们必须使用 Collection,ReadOnlyCollection,...... 所以,在方法是公共(public)的情况下,它的参数和它的返回值必须是 Collection、ReadOnlyCollection、...

对吗?

请您参考如下方法:

关于输入参数,通常使用最不具体的类型更灵活。例如,如果您的方法要做的只是枚举作为参数传递的集合中的项目,那么接受 IEnumerable 会更加灵活。

例如,考虑一个接受客户集合参数的方法“ProcessCustomers”:

public void ProcessCustomers(IEnumerable<Customer> customers) 
{ 
   ... implementation ... 
} 

如果您将参数声明为 IEnumerable ,您的调用者可以使用如下代码轻松传入集合的一个子集(NET 3.5 之前的版本:对于 .NET 3.5,您可以使用 lambda 表达式):

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 。有关为什么会这样的讨论,请参阅 this blog entry来自代码分析 (FxCop) 团队。