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