• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
博雅居
要想跟上时代,就得不断学习!
博客园    首页    新随笔    联系   管理    订阅  订阅
使用扩展方法(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);
}
}
}

 

If opportunity doesn’t knock, build a door
posted on 2015-10-22 13:59  博雅居  阅读(178)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3