首页 > Web开发 > 详细

MVC 中使用扩展方法

时间:2015-01-16 12:38:09      阅读:383      评论:0      收藏:0      [点我收藏+]

 扩展方法(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 中使用扩展方法

原文:http://www.cnblogs.com/yrup/p/4228232.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!