链式编程学习之练习篇

C#之链式编程(函数模式编程),最近很好像很火,我也尝试练习下。

学习链式编程 需要懂两个知识点:

1.必须会扩展方法

2.lambda+(Func,Action)

好了,下面是我的学习代码:

class Program
    {
        // study chained call 链式调用
        static void Main(string[] args)
        {
            //One 
            //Product p = new Product() { ProductName = "iphone5", Price = 300 }.First().Sencond().Third();
            
            //Two

            List<Product> list = new List<Product>()
            {
                new Product{ProductName="iphone5",Price=300},
                new Product{ProductName="iphone4s",Price=200},
                new Product{ProductName="ipad4",Price=100}
            };


            var s = list.GetIphone<Product, Product>(p =>
            {
                if (p.ProductName.Contains("iphone"))
                {
                    return p;
                }
                else
                    return null;
            }).getFirst<Product>();

            Console.WriteLine(s.Price);
            
            Console.ReadKey();
            
        }
    }

    public class Product
    {
        public string ProductName { get; set; }
        public int Price { get; set; }

        public Product First()
        {
            Console.WriteLine("First");
            return this;
        }
        public Product Sencond()
        {
            Console.WriteLine("Second");
            return this;
        }
        public Product Third()
        {
            Console.WriteLine("Third");
            return this;
        }
    }

    static class ProductExtension
    {
        
        //get iphone
        public static IEnumerable<TResult> GetIphone<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
        {

            foreach (var t in source)
            {

                if (selector(t) != null)
                {
                    yield return selector(t);
                }
            }
            
        }

        //get first
        public static Tsource getFirst<Tsource>(this IEnumerable<Tsource> ilist)
        {
            return ilist.First();
        }
        
    


    }

 

posted on 2013-08-10 14:16  ~紫鱼~  阅读(780)  评论(0编辑  收藏  举报