zoukankan      html  css  js  c++  java
  • 灵活的运用Model类

    1.定义接口

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace EssentialTools.Models
    {
        public interface IValueCalculator
        {
            decimal ValueProducts(IEnumerable<Product> products);
        }
    }
    

    2.继承接口

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace EssentialTools.Models
    {
        public class LinqValueCalculator : IValueCalculator
        {
            public decimal ValueProducts(IEnumerable<Product> products)
            {
                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 IEnumerable<Product> Products { 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;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Value</title>
    </head>
    <body>
        <div>
            Total value is $@Model
        </div>
    </body>
    </html>
    
  • 相关阅读:
    [Typescript] Augmenting Modules with Declarations
    [Postgres] On conflict Do Something Clause in Postgres
    [React] Debug Custom React Hooks With useDebugValue
    为什么不推荐通过Executors直接创建线程池
    JAVA线程池使用注意事项
    Java线程池使用的注意事项
    分布式事务(六)总结提高
    分布式事务(五)源码详解
    分布式事务(三)mysql对XA协议的支持
    分布式事务(二)Java事务API(JTA)规范
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/6946493.html
Copyright © 2011-2022 走看看