扩展方法(Extension Method)是给那些不是你拥有、因而不能直接修改的类添加方法的一种方便的办法。

一、使用扩展方法

1、定义一个购物车的类-ShoppingCart

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Demo.Models
{
public class ShoppingCart:IEnumerable<Product>
{
public List<Product> Products { get; set; } }
}

2、定义一个扩展方法

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Demo.Models
{
public static class MyExtensionMethods
{
public static decimal TotalPrices(this ShoppingCart cartParam)
{
decimal total = ;
foreach (Product prod in cartParam.Products)
{
total += prod.Price;
}
return total;
} }
}

this 关键字把TotalPrices定义为一个扩展方法 ShoppingCart 告诉。net 这个扩展方法运用与那个类

3、运用扩展方法

 public ViewResult UserExtension()
{
//创建并填充ShoppingCart
ShoppingCart cart = new ShoppingCart
{
Products = new List<Product>{
new Product{Name="kayak",Price=275M},//皮划艇
new Product{Name="Lifejacket",Price=48.95M},//休闲夹克
new Product{Name="Soccer ball",Price=19.50M},//足球
new Product{Name="Corner flag",Price=34.95M}//角旗
}
};
//求去购物车中的产品总价
decimal cartTotal = cart.TotalPrices();
return View("Result", (object)String.Format("Total:{0:c}", cartTotal));
}

4、结果展示

 二、对接口运用扩展方法

1、在ShoppingCart类中实现接口

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Demo.Models
{
public class ShoppingCart:IEnumerable<Product>
{
public List<Product> Products { get; set; }
public IEnumerator<Product> GetEnumerator()
{
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}

2、在接口上工作的扩展方法

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Demo.Models
{
public static class MyExtensionMethods
{ public static decimal TotalPrices(this IEnumerable<Product> productEnum)
{
decimal total=;
13 foreach(Product prod in productEnum)
14 {
15 total += prod.Price;
}
return total;
}
}
}

3、将扩展方法运用于同一接口的不同实现

  public ViewResult UseExtensionEnumerable()
{
IEnumerable<Product> products = new ShoppingCart
{
Products = new List<Product>{
new Product{Name="kayak",Price=275M},//皮划艇
new Product{Name="Lifejacket",Price=48.95M},//休闲夹克
new Product{Name="Soccer ball",Price=19.50M},//足球
new Product{Name="Corner flag",Price=34.95M}//角旗
}
};
Product[] productArary ={
new Product{Name="kayak",Price=375M},//皮划艇
new Product{Name="Lifejacket",Price=48.95M},//休闲夹克
new Product{Name="Soccer ball",Price=19.50M},//足球
new Product{Name="Corner flag",Price=34.95M}//角旗
};
//获取购物车中的产品总价
decimal cartTotal = products.TotalPrices();
//获取数组中产品的总价
decimal arrayTotal = productArary.TotalPrices();
return View("Result",(object)String.Format("Cart Total:{0},Array Total:{1}",cartTotal,arrayTotal));
}

4、结果展示

三、创建过滤扩展方法

1、

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Demo.Models
{
public static class MyExtensionMethods
{
public static IEnumerable<Product> FilterByCategory(this IEnumerable<Product> productEnum, string categoryParm)
{
foreach (Product prod in productEnum)
{
if (prod.Category == categoryParm)
{
yield return prod;
}
}
}
}
}

2、使用过滤扩展方法

 public ViewResult UseFilterExtensionMethod()
{
IEnumerable<Product> products = new ShoppingCart
{
Products = new List<Product>{
new Product{Name="kayak",Category="Watersports",Price=375M},//皮划艇
new Product{Name="Lifejacket",Category="Watersports",Price=48.95M},//休闲夹克
new Product{Name="Soccer ball",Category="Soccer",Price=19.50M},//足球
new Product{Name="Corner flag",Category="Soccer",Price=34.95M}//角旗
}
};
decimal total = ;
foreach (Product prod in products.FilterByCategory("Soccer"))
{
total += prod.Price;
}
return View("Result",(object)String.Format("Total:{0}",total));
}

3、结果展示

只用Soccer分类中的价格被返回累加出来。

MVC 中使用扩展方法的更多相关文章

  1. ASP.NET + MVC5 入门完整教程四---MVC 中使用扩展方法

    https://blog.csdn.net/qq_21419015/article/details/80433640 1.示例项目准备1)项目创建新建一个项目,命名为LanguageFeatures ...

  2. Enum扩展及MVC中DropDownListFor扩展方法的使用

    public enum SearchState { /// <summary> /// 全部 /// </summary> [Description("全部" ...

  3. mvc给html扩展方法:

    mvc给html扩展方法: 注意:扩展方法和所在的类都必须是 public static如果在页面直接使用新扩展的方法,需要web.config里把Web.Helper名称命名空间加上,页面才能访问到 ...

  4. Mvc 分页栏扩展方法

    using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Sy ...

  5. C#3.0中的扩展方法

    在实际应用中,开发者完成代码的编译后,除非重新编译更改后的代码,否则开发者很难在原有代码中添加新的功能. 在C#3.0中,提供了一个扩展方法的新特性,可以使得开发者在编译后的程序集里边添加相关的方法, ...

  6. 记录C#中的扩展方法

    C#中的扩展方法. 系统自带的类型,我们无法去修改: 修改源代码需要较大的精力,而且可能会带来错误: 我们只是需要一个或者较少的几个方法,修改源代码费时费力: 被扩展的类是sealed的,不能被继承: ...

  7. C#编程(六十一)------------LINQ中的扩展方法

    原文链接: http://blog.csdn.net/shanyongxu/article/details/47208401 LINQ中的扩展方法 LINQ中where扩展方法,要想使用,必须导入us ...

  8. objective-C中的扩展方法与partial class

     在c#中要扩展一个现有类非常easy,比方这样: ? 1 2 3 4 5 6 7 public static class Utils {     public static void PrintTo ...

  9. C#中的扩展方法(向已有类添加方法,但无需创建新的派生类型)

    C#中的扩展方法 扩展方法使你能够向现有类型"添加"方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样 ...

随机推荐

  1. 100个经典的C算法

    1.题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔 子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数 为多少? #include<stdio.h&g ...

  2. Linux中yum和apt-get用法及区别

    Linux中yum和apt-get用法及区别   一般来说著名的linux系统基本上分两大类:   1.RedHat系列:Redhat.Centos.Fedora等   2.Debian系列:Debi ...

  3. 图解 javascript 作用域链

    还是之前那一段简单的javascript代码: window.onload=function(){ function sub(a,b){ return a-b; } var result=sub(10 ...

  4. poj 3686

    The Windy's Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 3791   Accepted: 1631 Descr ...

  5. Hungary(匈牙利算法)——二分图最大匹配

    在复习匈牙利算法的时候,发现这么一篇介绍匈牙利算法的文章,非常通俗易懂,所以就借鉴过来了. 复杂度:邻接矩阵:O(v^3)邻接表:O(V*E) 附上链接:趣写算法系列之--匈牙利算法 下面就附上代码吧 ...

  6. POJ 2591 1338 2545 2247(数列递归衍生问题,思路挺妙)

    四道题的难度: 2591<1338<2545<2247 POJ 2591 Set Definition: 这是从discuss里看来的,写的挺好,直接copy,根据我的代码稍有改动( ...

  7. [C++]类的继承与派生

    继承性是面向对象程序设计的第二大特性,它允许在既有类的基础上创建新类,新类可以继承既有类的数据成员和成员函数,可以添加自己特有的数据成员和成员函数,还可以对既有类中的成员函数重新定义.利用类的继承和派 ...

  8. ***codeigniter 2.2 affected_rows()返回值不准确

    http://blog.icodeu.com/?p=596 问题描述今天在完成一个项目调用想要检验一下计划插入的数据是否都正常插入了.调用insert_batch()方法插入一百多条数据的时候发现af ...

  9. UVALive 6187 Never Wait for Weights 带权并查集

    题意:每次给出每两个数之间的大小差值.在给出关系的过程中插入询问:数a和数b的差值,若不能确定,输出UNKNOWN 解法:相对大小关系的处理:并查集 1.给出两点的相对大小关系后,找到两个点的根节点, ...

  10. 【转】SQL Server T-SQL写文本文件

    原文:http://www.nigelrivett.net/SQLTsql/WriteTextFile.html The are several methods of creating text fi ...