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. curl 基本用法

    curl usage: curl [options...] <url> $ curl -h -o, --output <file> 写入到文件,而不是输出到stdout -O ...

  2. 聊聊智能指针 auto_ptr、shared_ptr、weak_ptr和unique_ptr

    本文为转载:https://www.cnblogs.com/zeppelin5/p/10083597.html,对作者有些地方做了修正. 手写代码是理解C++的最好办法,以几个例子说明C++四个智能指 ...

  3. Local changes were not restore

    问题是这样的: 更新代码的时候出现这个弹框,不能更新最新代码 解决如下: 直接点击Clear [注意:这个操作是放弃本地所有的修改,如果要找回代码千万不要点击] 再点击Apply Stash  就可以 ...

  4. xadmin使用

    xadmin使用 官方 使用参考

  5. js 时间格式转换

    js时间格式转换 格式化时间转成时间戳 //格式化转时间戳(单位秒) function strtotime(strtime) { strtime = strtime.substring(0, 19); ...

  6. puthon 字典的 .update() 方法

    1.可以直接更新字典 2.也可以用等号连接,更新一个可迭代对象.

  7. 安装Docker到CentOS(YUM)

    运行环境 系统版本:CentOS Linux release 7.3.1611 (Core) 软件版本:Docker 17.12.1-ce 硬件配置:无 安装过程 1.配置YUM-Docker存储库 ...

  8. 从首个IMO季军谈起 作者 : 付云皓

    刚刚过去的IMO,中国史无前例地获得了第三名,也是自1997年来近20年首次跌出前二.感谢微信等社交软件,相信现在这个新闻已经以火箭的速度传播了. 作为一个与数学竞赛及IMO打了多年交道的人,我一直有 ...

  9. js面向对象怎么理解

    js面向对象怎么理解 <一>. 认识对象.首先要认识对象:在编程中,对象(object)是具体的某一个实例,唯一的某一个个体.如:电脑就是一个统称,而你面前的这一台电脑就是对象.而电脑的统 ...

  10. Python Django文件上传

    文件保存本地 view视图 def update(request): if request.method =='GET': return render(request,'update.html') e ...