2008-10-07 44 views
1

我和一位朋友討論了一個方法的返回/輸入值中集合的用法。他告訴我,我們必須使用 --返回值的派生類型最多。 - 輸入參數的最小派生類型。什麼是參數/返回值(集合)的代碼約定

所以,這意味着,例如,一個方法必須獲取一個ReadOnlyCollection作爲參數,並返回一個List。而且,他說我們絕不能在公開API中使用List或Dictionary,而我們必須使用Collection,ReadOnlyCollection,...因此,在方法是公共的情況下,它的參數及其參數返回值必須是Collection,ReadOnlyCollection,...

是不是正確?

回答

8

關於輸入參數,使用最小特定類型通常更靈活。例如,如果您的所有方法都要枚舉作爲參數傳遞的集合中的項目,那麼接受IEnumerable <T>會更靈活。

例如,考慮接受一個參數,就是客戶的集合的方法「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指導建議不要暴露名單<牛逼>。有關此原因的討論,請參閱代碼分析(FxCop)團隊的this blog entry

0

我傾向於同意不在API中返回或使用列表或字典作爲參數,因爲它確實限制了開發者定位API。相反,返回或傳遞IEnumerable>的效果非常好。

粗糙的,這一切都取決於應用程序。只是我的觀點。