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

use*_*703 1 c#

我和一位朋友就一个方法的返回值/输入值中的集合用法进行了一些讨论.他告诉我,我们必须使用 - 返回值的派生类型最多. - 输入参数的派生类型最少.

因此,这意味着,例如,方法必须将ReadOnlyCollection作为参数,并返回List.

而且,他说我们不能在publics API中使用List或Dictionary,而我们必须使用,而不是Collection,ReadOnlyCollection,......所以,在方法是public的情况下,它的参数和返回值必须是Collection,ReadOnlyCollection,......

这样对吗 ?

Joe*_*Joe 8

关于输入参数,使用最不具体的类型通常更灵活.例如,如果您要执行的所有方法都是枚举作为参数传递的集合中的项目,则接受IEnumerable <T>会更灵活.

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

public void ProcessCustomers(IEnumerable<Customer> customers)
{
   ... implementation ...
}
Run Code Online (Sandbox Code Playgroud)

如果将参数声明为IEnumerable <Customer>,则调用者可以使用以下代码轻松传入集合的子集(在.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);
...
Run Code Online (Sandbox Code Playgroud)

一般来说,MS指南建议不要暴露List <T>.有关为何如此的讨论,请参阅代码分析(FxCop)团队中的此博客条目.