zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Cache 在选择的几点思考
    英语12种记忆单词的方法
    对啊英语音标---二、ghywr这些辅音怎么发音
    日常英语---八、REBOOT
    日常英语---一、纸质版还是电子版
    日常英语---四、vis.js是什么
    日常英语---二、注册google的api的key
    日常英语---七、[Updated November 14 at 4:10 PM PST] Scheduled Game Update
    日常英语---六、Maplestory Illium
    日常英语---三、网页查找单词用什么
  • 原文地址:https://www.cnblogs.com/qianxingdewoniu/p/5436344.html
Copyright © 2011-2022 走看看