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:字段与属性的区分,属性一般是带有getter (get) 和/或 setter (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