標籤:
擴充方法(Extension Method)是給那些不是你擁有、因而不能直接修改的類添加方法的一種方便的辦法。
1、定義一個購物車的類-ShoppingCart
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Web; 6 7 namespace Demo.Models 8 { 9 public class ShoppingCart:IEnumerable<Product>10 {11 public List<Product> Products { get; set; }16 }17 }
2、定義一個擴充方法
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace Demo.Models 7 { 8 public static class MyExtensionMethods 9 {10 public static decimal TotalPrices(this ShoppingCart cartParam)11 {12 decimal total = 0;13 foreach (Product prod in cartParam.Products)14 {15 total += prod.Price;16 }17 return total;18 }28 }29 }
this 關鍵字把TotalPrices定義為一個擴充方法 ShoppingCart 告訴。net 這個擴充方法運用與那個類
3、運用擴充方法
1 public ViewResult UserExtension() 2 { 3 //建立並填充ShoppingCart 4 ShoppingCart cart = new ShoppingCart 5 { 6 Products = new List<Product>{ 7 new Product{Name="kayak",Price=275M},//皮划艇 8 new Product{Name="Lifejacket",Price=48.95M},//休閑夾克 9 new Product{Name="Soccer ball",Price=19.50M},//足球10 new Product{Name="Corner flag",Price=34.95M}//角旗11 }12 };13 //求去購物車中的產品總價14 decimal cartTotal = cart.TotalPrices();15 return View("Result", (object)String.Format("Total:{0:c}", cartTotal));16 }
4、結果展示
MVC 中使用擴充方法