https://blog.csdn.net/qq_21419015/article/details/80433640

1、示例项目准备
1)项目创建
新建一个项目,命名为LanguageFeatures ,选择 Empty (空白模板),选中 MVC 选项。在“Controllers”文件夹下创建 HomeController.cs 文件,修改默认Index 如下:

public string Index()
{
return "Navigate to a URL to show an example";
}
在Index上右键添加视图,在Views\Home\ 下出现Index.cshtml ,右键,在浏览器查看,效果如下:

2)添加引用
添加 System.Net.Http 程序集,该程序集默认不会添加到MVC项目中。在VS中的“Project(项目)”菜单选择“Add Reference(添加引用)”,打开“Reference Manager(引用管理器)”窗口,选择“Assemblies(程序集)”,选中“System.Net.Http”选项,如下所示:

2、使用自动实现的属性
常规的C#上属性可以暴露类的数据片段,这种数据片段与设置和接收数据采用了一种松耦合的方式。在 "Models"文件夹下新建一个 Product.cs 类:

namespace LanguageFeatures.Models
{
  public class Product
  {
    //字段
    private string name;
    //属性
    //自动实现属性{ get; set; }
    public int ProductID { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }     //实现自定义get,若需要set,则同时实现set;不可以自动实现set    
    public string Name
    {
      get { return ProductID + name; }
      set { name = value; }
    }
  }
}

  

ps:字段与属性的区分,属性一般是带有get和/或set块的成员

在HomeController.cs 中如下设置:添加一个方法

public ViewResult AutoProperty()
{
  //创建一个新的Product对象
  Product myProduct = new Product();
  //设置属性
  myProduct.Name = "KaKa";
  //读取属性
  string productName = myProduct.Name;
  //生成视图
  return View("Result", (object)String.Format("Product namae:{0}", productName));
}

在空白处右键,弹出菜单选择添加视图,命名Result ,内容如下:

@model String
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CreateProduct</title> 
</head>
<body>
<div> 
@Model
</div>
</body>
</html>
再在 AutoProperty 上右键添加视图,在\Home\AutoProperty.cshtml 右键,在浏览器中查看:

3、使用扩展方法

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

在Models 文件夹中新建 ShoppingCart.cs 文件,他表示 Products 对象集合。

using System;
using System.Collections;//实现接口
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LanguageFeatures.Models
{
public class ShoppingCart

{

//封装Product类
public List<Product> Products { get; set; }
}
}
一个简单的类,作用就是封装一个Products对象的列表。现在,假设我们需要确定ShoppingCart 类中的 Product对象总值,但是不能够修改这个类(已经假设这个类来自第三方,没有源代码,只有一个ShoppingCart,我们没办法操作ShoppingCart类内Product对象的值),这时候可以运用扩展方法来实现我们的功能。在Models下新建 MyExtensionMethod.cs 类。

public static class MyExtensionMethod
{
public static decimal TotalPrices(this ShoppingCart cartParam)
{
decimal total = 0;
foreach (Product pro in cartParam.Products)
{
total += pro.Price;
}
return total;
}
}
第一个参数前的this 关键字把 TotalPrices标记为一个扩展方法,第一个参数告诉 .NET,这个扩展方法运用那个类----此例指ShoppingCart,cartParam来引用ShoppingCart 类的实例。这个扩展方法枚举了 ShoppingCart 下所有的 Product 并返回Products.Price属性总和,下面在Home控制器中如何应用。新建一个名为UseExtension的动作方法

public ViewResult UseExtension()
{
//创建并填充ShoppingCart
ShoppingCart cart = new ShoppingCart
{
Products = new List<Product>
{
new Product {Name="Kaka",Price=275M },
new Product {Name="wangKa",Price=48.25M },
new Product {Name="wangKaka",Price=18.95M },
new Product {Name="KawangKa",Price=34.25M }
}
};
decimal cartTotal = cart.TotalPrices();

return View("Result", (object)String.Format("Total:{0:c}", cartTotal));
}
新建UseExtension视图,右键浏览器查看;

4、对接口运用扩展方法
扩展方法也可以运用在一个接口的扩展方法,并允许实现这个接口的所有类上调用这个扩展方法。同样在ShoppingCart类中实现  IEnumerable<Product> 接口的ShoppingCart类:

using System;
using System.Collections;//实现接口
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LanguageFeatures.Models
{
public class ShoppingCart : IEnumerable<Product>{
//封装Product类
public List<Product> Products { get; set; }

public IEnumerator<Product> GetEnumerator()
{
return Products.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

}
}
在Models文件夹下MyExtensionMethod.cs 继续实现接口扩展方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LanguageFeatures.Models
{
public static class MyExtensionMethod
{
//扩展方法
public static decimal TotalPrices(this ShoppingCart cartParam)
{
decimal total = 0;
foreach (Product pro in cartParam.Products)
{
total += pro.Price;
}
return total;
}

//接口扩展方法
public static decimal ITotalPrices(this IEnumerable<Product> productEnum)
{
decimal total = 0;
foreach (Product pro in productEnum)
{
total += pro.Price;
}
return total;
}

}
}
在Home控制器中如何应用。新建一个名为 UseExtensionEnumerable 的动作方法

public ViewResult UseExtensionEnumerable()
{
IEnumerable<Product> products = new ShoppingCart
{
Products = new List<Product>
{
new Product {Name="Kaka",Price=275M },
new Product {Name="wangKa",Price=48.95M },
new Product {Name="wangKaka",Price=19.50M },
new Product {Name="KawangKa",Price=39.25M }
}
};
//创建并填充ShoppingCart
Product[] productArrary =
{
new Product {Name="Kaka",Price=375M },
new Product {Name="wangKa",Price=48.95M },
new Product {Name="wangKaka",Price=19.50M },
new Product {Name="KawangKa",Price=34.95M }
};

//获取购物车中的产品总价
decimal cartTotal = products.ITotalPrices();

//获取数组中产品的总价
decimal arrayTotal = productArrary.ITotalPrices();

return View("Result", (object)String.Format("Cart Total:{0},Arrary Toal:{1}", cartTotal, arrayTotal));
}
添加UseExtensionEnumerable 视图,右键在浏览器中查看:

5、使用过滤扩展方法

最后演示的一种扩展方法可以对对象集合进行过滤,这是一种对 IEnumerable<T>进行操作,并且返回一个 IEnumerable<T> 结果,可以用 yield 关键字把选择条件运用于源数据。在Models文件夹下MyExtensionMethod.cs 继续实现过滤扩展方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LanguageFeatures.Models
{
public static class MyExtensionMethod
{
//扩展方法
public static decimal TotalPrices(this ShoppingCart cartParam)
{
decimal total = 0;
foreach (Product pro in cartParam.Products)
{
total += pro.Price;
}
return total;
}

//接口扩展方法
public static decimal ITotalPrices(this IEnumerable<Product> productEnum)
{
decimal total = 0;
foreach (Product pro in productEnum)
{
total += pro.Price;
}
return total;
}

//过滤扩展方法
public static IEnumerable<Product> FilterByCategory(this IEnumerable<Product> productEnum,string categortyParam)
{
foreach (Product pro in productEnum)
{
if(pro.Category== categortyParam)
{
yield return pro;
}
}
}

}
}
FilterByCategory 扩展方法采用一个附加参数,允许在调用该方法时加入一个过滤条件,利用 Category 属性来过滤 Product 对象,不匹配的被丢弃。在HomeController.cs 中运用:

public ViewResult UseFilterExtensionEnumerable()
{
IEnumerable<Product> products = new ShoppingCart
{
Products = new List<Product>
{
new Product {Name="Kaka",Category="Watersports",Price=275M },
new Product {Name="wangKa",Category="Soccer",Price=48.95M },
new Product {Name="wangKaka",Category="Watersports",Price=19.50M },
new Product {Name="KawangKa",Category="Soccer",Price=39.25M }
}
};

decimal cartTotal = 0;

foreach (Product pro in products.FilterByCategory("Soccer"))
{
cartTotal += pro.Price;
}
return View("Result", (object)String.Format("CartTotal:{0}", cartTotal));
}
添加 UseFilterExtensionEnumerable 视图,右键在浏览器中查看:

资源下载:https://download.csdn.net/download/qq_21419015/10435081

ASP.NET + MVC5 入门完整教程四---MVC 中使用扩展方法的更多相关文章

  1. ASP.NET + MVC5 入门完整教程七 -—-- MVC基本工具(上)

    https://blog.csdn.net/qq_21419015/article/details/80474956 这里主要介绍三类工具之一的 依赖项注入(DI)容器,其他两类 单元测试框架和模仿工 ...

  2. ASP.NET + MVC5 入门完整教程七 -—-- MVC基本工具(下)

    https://blog.csdn.net/qq_21419015/article/details/80493633 Visual Stdio 的单元测试

  3. ASP.NET + MVC5 入门完整教程三 (下) ---MVC 松耦合

    建立松耦合组件 MVC 模式最重要的特性之一视他支持关注分离,希望应用程序中的组件尽可能独立,只有很少的几个可控依赖项.在理想的情况下,每个组件都不了解其他组件,而只是通过抽象接口来处理应用程序的其他 ...

  4. ASP.NET + MVC5 入门完整教程八 -—-- 一个完整的应用程序(上)

    https://blog.csdn.net/qq_21419015/article/details/80509513 SportsStore 1.开始创建Visual Studio 解决方案和项目这里 ...

  5. ASP.NET + MVC5 入门完整教程八 -—-- 一个完整的应用程序(下)

    https://blog.csdn.net/qq_21419015/article/details/80802931 SportsStore 1.导航 添加导航控件 如果客户能够通过产品列表进行分类导 ...

  6. ASP.NET + MVC5 入门完整教程三 (上) ---第一个MVC项目

    https://blog.csdn.net/qq_21419015/article/details/80420815 第一个MVC应用程序 1创建MVC项目 打开VS ,File--新建--项目,选择 ...

  7. ASP.NET + MVC5 入门完整教程五 --- Razor (模型与布局)

    https://blog.csdn.net/qq_21419015/article/details/80451895 1.准备示例项目 为了演示Razor,使用VS创建一个名称为“Razor”的新项目 ...

  8. ASP.NET + MVC5 入门完整教程二

    原文链接:https://blog.csdn.net/qq_21419015/article/details/80318046 从前端UI开始 MVC分离的比较好,开发顺序没有特别要求,先开发哪一部分 ...

  9. asp.net + MVC5 入门完整教程一

    原文链接:https://blog.csdn.net/qq_21419015/article/details/80311918原创凌霜残雪 最后发布于2018-05-14 17:26:30 阅读数 3 ...

随机推荐

  1. th:object、th:field、th:value 和 #dates.format 的冲突问题处理

    若直接使用th:object 分解对象后,在搭配th:field="${#dates"使用#dates.format会抛出下面的异常: ---------------------- ...

  2. 网络共享服务(二)之NFS

    NFS: Network File System,是一种基于TCP/IP传输的网络文件系统协议,最初由SUN公司开发.通过使用NFS协议,客户机可以像访问本地目录一样访问服务器中的共享资源.但是,NF ...

  3. 【整理】IC失效机理(持续更新)

    IC  四种常见失效机理如下: EM     -- electron migration,电子迁移)TDDB -- time dependent dielectric breakdown,与时间相关电 ...

  4. luogu P1736 创意吃鱼法

    #include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #i ...

  5. 08-SV面向对象编程的高级技巧指南

    1.原始类与扩展类 (1)原始类被称为父类或者超类,扩展类被称为派生类或者子类.扩展类可以直接访问原始类和其本身的所有变量,应该将原始类中的子程序定义成虚拟的,这样它们就可以在扩展类中重定义.new函 ...

  6. poj1042题解

    h [1,16] hours all_v=h*12 intervals n [2,25] lakes fi inital intervals fi-di*v v [0,all_v) 题意,做每件事情的 ...

  7. linux-crond_计划任务

    定时计划任务 主要文件介绍: [root@nginx ~]# ll /etc/cron* -d drwxr-xr-x. 2 root root 21 7月 11 20:28 /etc/cron.d d ...

  8. linux - 服务器性能评估

    影响Linux服务器性能的因素 cpu 内存 磁盘IO 网络IO 系统性能评估标准 影响性能因素 好 坏 糟糕 CPU user% + sys%< 70% user% + sys%= 85% u ...

  9. Ubuntu16.04突然断网

    配置文件: sudo gedit /etc/network/interfaces 重启网络: 1.sudo /etc/init.d/networking restart 2.sudo service ...

  10. 使用Image Sharp 对二维码图片中间加入logo图片

    1.在NuGet包源加入Image Sharp包源 2.在需要用到Image Sharp的项目中安装以下的插件 3.调用图片上绘制图片的方法