C#Extension Methods 扩展方法使用

来源:互联网 发布:人工智能 呼叫中心 编辑:程序博客网 时间:2024/06/05 06:10

对已知类的方法进行扩展

一、已知类

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();


0 0
原创粉丝点击