關於輸入參數,使用最小特定類型通常更靈活。例如,如果您的所有方法都要枚舉作爲參數傳遞的集合中的項目,那麼接受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。
來源
2008-10-07 08:46:43
Joe