设为首页 加入收藏

TOP

C#扩展方法原理及其使用(一)
2019-09-17 18:23:43 】 浏览:37
Tags:扩展 方法 原理 及其 使用
1、写在前面

今天群里一个小伙伴问了这样一个问题,扩展方法与实例方法的执行顺序是什么样子的,谁先谁后(这个问题会在文章结尾回答)。所以写了这边文章,力图从原理角度解释扩展方法及其使用。

以下为主要内容:

  • 什么是扩展方法
  • 扩展方法原理及自定义扩展方法
  • 扩展方法的使用及其注意事项
 
2、什么是扩展方法

      一般而言,扩展方法为现有类型添加新的方法(从面向对象的角度来说,是为现有对象添加新的行为)而无需修改原有类型,这是一种无侵入而且非常安全的方式。扩展方法是静态的,它的使用和其他实例方法几乎没有什么区别。常见的扩展方法有Linq扩展、有IEnumerable扩展等。
     先让我们来感受一下.NET中自带的扩展方法,其中OrderBy和Aggregate都是系统自带的扩展方法

using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> lst = new List<int> { 2, 1, 4, 3 };

            string result = lst.OrderBy(p => p).Aggregate(string.Empty, (next, p) => next += p + ",");

            Console.WriteLine(result);

            Console.ReadLine();
        }
    }
}

输出结果:

image

是不是感觉扩展方法很优美,使用起来和实例方法几乎没有区别。不得不说.NET在这方面做得很精致,很让人钦佩,那么接下来我们来看看扩展方法的原理

3、扩展方法原理及自定义扩展方法

首先我们,先看看如何自定义扩展方法

using System;
using TestExtension;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("2".ToInt32());

            Console.ReadLine();
        }
    }
}

namespace TestExtension
{
    public static class StringExtension
    {
        public static int ToInt32(this string str)
        {
            if (int.TryParse(str, out int result))
            {
                return result;
            }

            throw new ArgumentException("无法转换为Int32类型");
        }
    }
}

通过以上实例,我们可以知道自定义扩展方法需要做到:

  • 必须是静态类,扩展方法也为静态方法
  • 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符
  • 在调用代码中,如何不再同一个命名空间,需要添加 using 指令,导入需要调用的扩展方法所在的命名空间
  • 需要注意的是,第一个this标记的参数并非是实参,而是标识该扩展所指定的类型,调用的时候只需要提供this后的形参即可

接下来我们来探究一下扩展方法反编译后的效果:

这是StringExtension编译后的代码,可以看到扩展方法在编译后被标记了ExtensionAttribute这个特性,也就是说扩展方法在编译期就已经被绑定成扩展方法了

.class public auto ansi abstract sealed beforefieldinit TestExtension.StringExtension
    extends [System.Runtime]System.Object
{
    .custom instance void 
[System.Runtime]System.Runtime.CompilerServices.ExtensionAttribute
::.ctor() = (
        01 00 00 00
    )
    // Methods
    .method public hidebysig static 
        int32 ToInt32 (
            string str
        ) cil managed 
    {
        .custom instance void 
[System.Runtime]System.Runtime.CompilerServices.ExtensionAttribute
::.ctor() = (
            01 00 00 00
        )
        // Method begins at RVA 0x2050
        // Code size 31 (0x1f)
        .maxstack 2
        .locals init (
            [0] int32,
            [1] bool,
            [2] int32
        )

        IL_0000: nop
        IL_0001: ldarg.0
        IL_0002: ldloca.s 0
        IL_0004: call bool [System.Runtime]System.Int32::TryParse(string, int32&)
        IL_0009: stloc.1
        IL_000a: ldloc.1
        IL_000b: brfalse.s IL_0012

        IL_000d: nop
        IL_000e: ldloc.0
        IL_000f: stloc.2
        IL_0010: br.s IL_001d

        IL_0012: ldstr "无法转换为Int32类型"
        IL_0017: newobj instance void [System.Runtime]System.ArgumentException::.ctor(string)
        IL_001c: throw

        IL_001d: ldloc.2
        IL_001e: ret
    } // end of method StringExtension::ToInt32

} // end of class TestExtension.StringExtension

我们看一下调用后的效果,和直接调用静态方法一样TestExtension.StringExtension::ToInt32(string) ,至此,我们已经知道了扩展方法的使用了,编译器绑定,底层调用和静态调用一直,这也解释了一个问题,就是当类型为空的时候,为什么调用扩展方法了

.namespace Test
{
    .class private auto ansi beforefieldinit Test.Program
        extends [System.Runtime]System.Object
    {
        // Methods
        .method private hidebysig static 
            void Main (
                string[] args
            ) cil managed 
        {
            // Method begins at RVA 0x207b
            // C
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Gzip压缩和解压 下一篇wpf 水波进度条 用户控件

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目