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 Listlist = new List () { new Product{ProductName="iphone5",Price=300}, new Product{ProductName="iphone4s",Price=200}, new Product{ProductName="ipad4",Price=100} }; var s = list.GetIphone (p => { if (p.ProductName.Contains("iphone")) { return p; } else return null; }).getFirst (); 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 GetIphone (this IEnumerable source, Func selector) { foreach (var t in source) { if (selector(t) != null) { yield return selector(t); } } } //get first public static Tsource getFirst (this IEnumerable ilist) { return ilist.First(); } }