December 2007
Intermediate to advanced
896 pages
19h 57m
English
You want to be able to perform multiple operations on an entire collection of objects at once, while keeping the operations functionally segmented.
Use a functor (or function object, as it is also known) as the vehicle for transforming the collection. A functor is any object that can be called as a function. Examples of this are a delegate, a function, a function pointer, or even an object that defines operator() for us C/C++ converts.
Needing to perform multiple operations on a collection is a reasonably common thing in software. Let's say that you have a stock portfolio with a bunch of stocks in it. Your StockPortfolio class would have a List of Stock object and would be able to add stocks:
public class StockPortfolio : IEnumerable<Stock> { List<Stock> _stocks; public StockPortfolio( ) { _stocks = new List<Stock>( ); } public void Add(string ticker, double gainLoss) { _stocks.Add(new Stock( ) {Ticker=ticker, GainLoss=gainLoss}); } public IEnumerable<Stock> GetWorstPerformers(int topNumber) { return _stocks.OrderBy( (Stock stock) => stock.GainLoss).Take(topNumber); } public void SellStocks(IEnumerable<Stock> stocks) { foreach(Stock s in stocks) _stocks.Remove(s); } public void PrintPortfolio(string title) { Console.WriteLine(title); _stocks.DisplayStocks( ); } #region IEnumerable<Stock> Members public IEnumerator<Stock> GetEnumerator( ) { return _stocks.GetEnumerator( ); } #endregion #region IEnumerable ...Read now
Unlock full access