MVC 中使用擴充方法

來源:互聯網
上載者:User

標籤:

 擴充方法(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 中使用擴充方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.