C#体贴之处点滴 - 如果打算写一个类似System.Linq.Enumerable.Where的extention method

说的是C#如何体贴程序员,而非.NET Framework。

 

如果打算写一个类似System.Linq.Enumerable.Where的extention method,假设命名为Filter,下面是C#为满足此需求下的功夫:

        public static IEnumerable<T> Filter<T>(this IEnumerable<T> source, Func<T, bool> predicate)    
        {
            if (source == null || predicate == null)
            {
                throw new ArgumentNullException();
            }
            return impl(source, predicate);
        }

        private static IEnumerable<T> impl<T>(IEnumerable<T> source, Func<T, bool> predicate)
        {
            foreach (T item in source)
            {
                if (predicate(item))
                {
                    yield return item;
                }
            }
        }

 

如果不依赖C#的语言糖衣,即上面的二个黑体关键字,纯粹依赖于framework来实现,就得费不少牛劲了。瞎猜一下,如果没有C#的体贴,也就不会有众多精彩纷呈的Linq Provider了!

 

下面是使用Filter的示例代码,Filter完全等价于Where!而且IDE Intellisense会识别到Filter, 如何,体贴不?

List<Product> products = Product.GetSampleProducts();

foreach (Product product in products.Filter(p => p.Weight > 0))  //可以换成Where

{

  Console.WriteLine (product);

}

 

posted @ 2011-10-26 08:04  James Leng  阅读(1067)  评论(3编辑  收藏  举报