Extension methods (Extension method) are a convenient way to add methods to classes that are not owned by you and thus cannot be modified directly.
1, define a shopping cart class-shoppingcart
1 usingSystem;2 usingSystem.Collections;3 usingSystem.Collections.Generic;4 usingSystem.Linq;5 usingsystem.web;6 7 namespaceDemo.models8 {9 Public classShoppingcart:ienumerable<product>Ten { One PublicList<product> Products {Get;Set; } - } -}
2. Define an extension method
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 6 namespaceDemo.models7 {8 Public Static classMyextensionmethods9 {Ten Public Static decimalTotalprices ( ThisShoppingCart Cartparam) One { A decimalTotal =0; - foreach(Product prodinchcartparam.products) - { theTotal + =Prod. Price; - } - returnTotal ; - } - } in}
The This keyword defines totalprices as an extension method ShoppingCart tells. NET this extension method applies to that class
3, the use of extension methods
1 PublicViewResult userextension ()2 {3 //Create and populate ShoppingCart4ShoppingCart cart =NewShoppingCart5 {6Products =NewList<product>{7 NewProduct{name="Kayak", price=275m},//Kayaking8 NewProduct{name="lifejacket", price=48.95M},//Casual Jackets9 NewProduct{name="Soccer Ball", price=19.50M},//FootballTen NewProduct{name="Corner Flag", price=34.95M}//Corner Flag One } A }; - //find the total price of the product in the shopping cart - decimal carttotal = cart. Totalprices (); the returnView ("Result", (Object) String.Format ("Total:{0:c}", Carttotal)); -}
4. Results display
Using extension methods in MVC