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. yamlapi接口测试框架

    1.思路: yamlapi支持unittest与pytest两种运行模式, yamlapi即为yaml文件+api测试的缩写, 可以看作是一个脚手架工具, 可以快速生成项目的各个目录与文件, 只需维护 ...

  2. Java开学测试-学生成绩管理系统

    题目: 1.定义 ScoreInformation 类,其中包括七个私有变量(stunumber, name, mathematicsscore, englishiscore,networkscore ...

  3. .net mvc接收参数为null的解决方案

    1.通过对象接收请求数据时的null 必须为对象的属性设置get与set private System.String _EMail = System.String.Empty; public Syst ...

  4. PAT (Basic Level) Practice (中文)1070 结绳 (25 分) (优先队列)

    给定一段一段的绳子,你需要把它们串成一条绳.每次串连的时候,是把两段绳子对折,再如下图所示套接在一起.这样得到的绳子又被当成是另一段绳子,可以再次对折去跟另一段绳子串连.每次串连后,原来两段绳子的长度 ...

  5. python 集合运算交集&并集&差集

    差集>>> #两个列表的差集3 >>> ret3 = list(set(a) ^ set(b)) #两个列表的差集 >>> ret4=list(s ...

  6. H5_0017:通过元素自定义属性值获取元素对象,并获取属性值

            // 通过元素的属性值查找对象         // document.querySelectorAll("[data]").forEach(function(e) ...

  7. java学习笔记之集合—ArrayList源码解析

    1.ArrayList简介 ArrayList是一个数组队列,与java中的数组的容量固定不同,它可以动态的实现容量的增涨.所以ArrayList也叫动态数组.当我们知道有多少个数据元素的时候,我们用 ...

  8. react-发表评论案例

    评论列表组件 import React from 'react' import CMTItem from './CmtItem.jsx' import CMTBox from './CmtBox.js ...

  9. 书写makefile的注意点

    1.空格 定义一个变量时用“foo = 1”这种形式,1后面千万不可以有空格,否则,foo的值为“1 ”.等于号和1之间的空格有无,并没有关系. 2.ifeq ifeq的形式是“ifeq ($(foo ...

  10. b站德云社相声合集

    每天都做德云小可爱呀 郭德纲于谦相声合集搜索: 75314217.75079477 62444678.60874866 60745041.60514509 之前在喜马拉雅上面听过,部分高清的要会员,只 ...