本文共 1951 字,大约阅读时间需要 6 分钟。
1.定义接口
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace EssentialTools.Models{ public interface IValueCalculator { decimal ValueProducts(IEnumerableproducts); }}
2.继承接口
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace EssentialTools.Models{ public class LinqValueCalculator : IValueCalculator { public decimal ValueProducts(IEnumerableproducts) { return products.Sum(p => p.Price); } }}
3.购物车,商品对象,计算商品总价方法
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace EssentialTools.Models{ public class ShoppingCart { private IValueCalculator calc; public ShoppingCart(IValueCalculator calcParam) { calc = calcParam; // 引入其他类帮助 } public IEnumerableProducts { get; set; } public decimal CalculateProductTotal() { return calc.ValueProducts(Products); } }}
4.控制器整合处理
private Product[] products = { new Product {Name = "Kayak", Category = "Watersports", Price = 275M}, 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} }; public ActionResult Index() { IValueCalculator calc = new LinqValueCalculator(); ShoppingCart cart = new ShoppingCart(calc) { Products = products }; // 购物车中的商品 decimal totalValue = cart.CalculateProductTotal(); return View(totalValue); }
5.页面展示
@model decimal@{ Layout = null;}Value Total value is $@Model
</html>
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6946493.html,如需转载请自行联系原作者