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);
    }
    }
    }
  • 相关阅读:
    java-并发解决方案
    linux-常用快捷键
    java-进程
    vim-常用快捷键
    数据库-事务
    spring-事务实现原理
    gdb
    x86 下的 struct 變數 member 擺放位置
    du 查看 資料夾 佔用空間
    ADC 計算時,階數的選擇
  • 原文地址:https://www.cnblogs.com/CandiceW/p/4900738.html
Copyright © 2011-2022 走看看