zoukankan      html  css  js  c++  java
  • 使用扩展方法(Chapter3 P39-41)

    namespace LanguageFeatures
    {
        public class ShoppingCart
        {
            public List<Product> Products { get; set; }
        }
    }

    假设无法修改上面的类,这时可以使用扩展方法获得所需功能

    namespace LanguageFeatures
    {
        public static class MyExtensionMethods
        {
            public static decimal TotalPrices(this ShoppingCart cartParam)//this 关键字将TotalPrices标注为扩展方法。
            {
                decimal total = 0;
                foreach (Product prod in cartParam.Products)
                {
                    total += prod.Price;
                }
                return total;
            }
        }
    }

    使用扩展方法

    namespace LanguageFeatures
    {
    public partial class Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    
    }
    
    protected string GetMessage()
    {
     
    
    ShoppingCart cart = new ShoppingCart
    {
    Products = new List<Product>
    {
    new Product {Name ="Kayak",Price=275M},
    new Product {Name ="Lifejacket",Price=48.95M},
    new Product {Name ="Soccer ball",Price=19.5M},
    new Product {Name ="Corner flag",Price=34.95M}
    
    }
    };
    decimal cartTotal = cart.TotalPrices();
    return String.Format("Total:{0:c}", cartTotal);
    }
    }
    }
  • 相关阅读:
    hdu 1269 迷宫城堡(强联通分量,基础)
    hdu 2102 A计划(BFS,基础)
    python 变量命名规范
    rpm常用选项
    memcached
    session共享
    Nginx高级使用
    nginx 反向代理
    Nginx基本使用
    github 建立博客
  • 原文地址:https://www.cnblogs.com/CandiceW/p/4900738.html
Copyright © 2011-2022 走看看