• C#中扩展方法


    什么是扩展方法?

    扩展方法顾名思义,就是允许向现有的“类型”添加方法,而无需创建派生类、重新编译或以其他方式修改原来类型。

    扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

    扩展方法和实例方法有何区别?

    通常只有在不得已(例如:不能修改原来的类型)的情况下才实现扩展方法,如果扩展方法和类型中定义的实例方法相同,则扩展方法不会被调用,因为实例方法的优先级高于扩展方法的优先级。。

    已用到的扩展方法:

    最常见的扩展方法是LINQ标准查询运算符,它将查询功能添加到现有的System.Collections.IEnumerable和System.Collection.Generic.IEnumerable<T>类型。若要使用标准查询运算符,请先使用using System.Linq指令将它们置于范围内。然后,任何实现了IEnumerable<T>的类型看起来都具有GroupBy<TSource,TKey>,Order<TSource,TKey>等实例方法。

    class ExtensionMethods2    
    {
    
        static void Main()
        {            
            int[] ints = { 10, 45, 15, 39, 21, 26 };
            var result = ints.OrderBy(g => g);
            foreach (var i in result)
            {
                System.Console.Write(i + " ");
            }           
        }        
    }
    //Output: 10 15 21 26 39 45

    如何增加一个扩展方法? 

      一、定义一个测试类型,其中包含一个实例方法,如下:  

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Demo_ExtensionMethod2
    {
        public class Test
        {
            public void InstanceMethod()
            {
                Console.WriteLine("I am a Instance Method!");
            }
        }
    }
    View Code

      二、定义一个扩展类型,其中包含一个扩展方法,以后如需新增扩展方法,在该类中新增方法放即可,主要要定义为static类型,如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Demo_ExtensionMethod2.ExtensionMethods
    {
        public static class MyExtensions
        {
            public static void ExtensionMethod(this Test test)
            {
                Console.WriteLine("I am a Extension Method!");
            }
        }
    }
    View Code

      三、使用时,切记要添加对扩展方法的引用,否则编译不过,如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Demo_ExtensionMethod2.ExtensionMethods;
    
    namespace Demo_ExtensionMethod2
    {
        class Program
        {
            static void Main(string[] args)
            {
                Test test = new Test();
                test.InstanceMethod();      //调用实例方法
                test.ExtensionMethod();     //调用扩展方法
    
                Console.Read();
            }
        }
    }
    View Code

    参考:https://msdn.microsoft.com/zh-cn/library/bb383977.aspx

  • 相关阅读:
    Sentinel实现熔断和限流
    Nacos 服务注册和配置中心
    SpringCloud Sleuth 分布式请求链路跟踪
    SpringCloud Stream消息驱动
    SpringCloud Bus消息总线
    SpringCloud Config分布式配置中心
    Geteway服务网关
    Hystrix断路器
    libecc:一个可移植的椭圆曲线密码学库
    第四十二个知识点:看看你的C代码为蒙哥马利乘法,你能确定它可能在哪里泄漏侧信道路吗?
  • 原文地址:https://www.cnblogs.com/qianxingdewoniu/p/5436344.html
Copyright © 2020-2023  润新知