对已知类的方法进行扩展
一、已知类
public class ShoppingCart : IEnumerable<Product> {
public List<Product> Products { get; set; }
public IEnumerator<Product> GetEnumerator() {
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
二、方法扩展
public static class MyExtensionMethods {
public static decimal TotalPrices(this IEnumerable<Product> productEnum) {
decimal total = 0;
foreach (Product prod in productEnum) {
total += prod.Price;
}
return total;
}
public static IEnumerable<Product> FilterByCategory(
this IEnumerable<Product> productEnum, string categoryParam) {
foreach (Product prod in productEnum) {
if (prod.Category == categoryParam) {
yield return prod;
}
}
}
}
三、实际使用
IEnumerable<Product> products = new ShoppingCart {
Products = new List<Product> {
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}
}
};
decimal total = products.FilterByCategory("Soccer").TotalPrices();