扩展方法的目的就是为一个现有的类型添加一个方法,现有类型既可以是int,string等数据类型,也可以是自定义的数据类型。
扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。例如,我们可以让Random类的所有实例对象拥有一个返回随机bool值的方法。我们不能对Random类本身进行修改,但可以对它进行扩展,如下代码所示:
//必须是静态类才可以添加扩展方法
static class Program {
/// <summary>
/// 随机返回 true 或 false
/// </summary>
/// <param name="random">this参数自动指定到Random的实例</param>
/// <returns></returns>
public static bool NextBool(this Random random) {
return random.NextDouble() > 0.5;
}
static void Main(string[] args) {
//调用扩展方法
Random rd = new Random();
bool bl = rd.NextBool();
Console.WriteLine(bl.ToString());
Console.ReadKey();
}
}
注意,扩展方法必须在非泛型的静态类中定义,上面的Program类如不加static修饰符则会报错。
我们可以创建一个接口的扩展方法,这样实现该接口的类都可以调用该扩展方法。看下面一个完整示例:
/// <summary>
/// 购物车类 (实现 IEnumerable<Product> 接口)
/// </summary>
public class ShoppingCart : IEnumerable<Product> {
public List<Product> Products { get; set; }
public IEnumerator<Product> GetEnumerator() {
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
/// <summary>
/// 定义一个静态类,用于实现扩展方法(注意:扩展方法必须定义在静态类中)
/// </summary>
public static class MyExtensionMethods {
/// <summary>
/// 计算商品总价钱
/// </summary>
public static decimal TotalPrices(this IEnumerable<Product> productEnum) {
decimal total = 0;
foreach (Product prod in productEnum) {
total += prod.Price;
}
return total;
}
}
class Program {
static void Main(string[] args) {
// 创建并初始化ShoppingCart实例,注入IEnumerable<Product>
IEnumerable<Product> products = new ShoppingCart {
Products = new List<Product> {
new Product {Name = "Kayak", Price = 275},
new Product {Name = "Lifejacket", Price = 48.95M},
new Product {Name = "Soccer ball", Price = 19.50M},
new Product {Name = "Corner flag", Price = 34.95M}
}
};
// 创建并初始化一个普通的Product数组
Product[] productArray = {
new Product {Name = "Kayak", Price = 275M},
new Product {Name = "Lifejacket", Price = 48.95M},
new Product {Name = "Soccer ball", Price = 19.50M},
new Product {Name = "Corner flag", Price = 34.95M}
};
// 取得商品总价钱:用接口的方式调用TotalPrices扩展方法。
decimal cartTotal = products.TotalPrices();
// 取得商品总价钱:用普通数组的方式调用TotalPrices扩展方法。
decimal arrayTotal = productArray.TotalPrices();
Console.WriteLine("Cart Total: {0:c}", cartTotal);
Console.WriteLine("Array Total: {0:c}", arrayTotal);
Console.ReadKey();
}
}
执行后输出如下结果: