您的位置:首页 > 其它

C#Extension Methods 扩展方法使用

2014-11-17 10:25 302 查看
对已知类的方法进行扩展

一、已知类

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: