zoukankan      html  css  js  c++  java
  • 扩展方法

    扩展方法的目的就是为一个现有的类型添加一个方法,现有类型既可以是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();
        }
    }

    执行后输出如下结果:

  • 相关阅读:
    PMP考试结束了,期待结果中。。。
    Windows Server 2008安装及配置Terminal Server
    CMMI分段式级别的易理解版本
    c# RoundUp函数
    管理学中的知名定律之阿尔布莱特法则
    Risk Categories
    如何躲开“责任”的逆袭
    一次失败的聚会
    【老孙随笔】属相影响你的职业前途吗?
    项目经理的超越(三)人际优先,做事上的超越
  • 原文地址:https://www.cnblogs.com/sylone/p/6098888.html
Copyright © 2011-2022 走看看