内部如何实现扩展方法 [英] How extension methods are implemented internally

查看:86
本文介绍了内部如何实现扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展方法如何在内部实现?我的意思是当编译器看到扩展方法的声明时发生什么,而在调用扩展方法时在运行时发生什么。



是否涉及反射?或者,当您拥有扩展方法时,其代码是否会在目标类类型元数据中注入代码,并带有一些其他标志,指出这是一种扩展方法,然后CLR知道如何处理?



因此,总的来说,到底发生了什么?

解决方案

正如其他同事已经说过的那样,这只是静态的方法。
关于编译器,我们可以说CLR甚至不知道扩展方法。
您可以尝试检查IL代码..



以下是示例

 静态类ExtendedString 
{
public static String TestMethod(this String str,String someParam)
{
return someParam;
}
}

静态void Main(string [] args)
{
String str = String.Empty;
Console.WriteLine(str.TestMethod( Hello World !!));
........
}

这是il代码。 b $ b IL_0007:ldloc.0
IL_0008:ldstr Hello World !!
IL_000d:调用字符串StringPooling.ExtendedString :: TestMethod(string,
字符串)
IL_0012:调用void [mscorlib] System.Console :: WriteLine(string)
IL_0017:nop

如您所见,这只是对静态方法的调用。
该方法未添加到类中,但是编译器使它看起来像这样。
反射层上,您唯一看到的区别是添加了CompilerServices.ExtensionAttribute。


How are extension methods implemented internally? I mean what happens when the compiler sees a declaration for an extension method and what happens at runtime when there is a call to an extension method.

Is reflection involved? Or when you have an extension method is its code injected in the target class type metadata with some additional flags noting that this is an extension method and then the CLR knows how to handle that?

So in general, what happens under the hood?

解决方案

As already have said by other colleagues it is just a static method. It is all about the compiler we can say that CLR even have no idea about extension methods. You can try to check IL code ..

Here is an example

static class ExtendedString
{
    public static String TestMethod(this String str, String someParam)
    {
        return someParam;
    }
}

static void Main(string[] args)
{
    String str = String.Empty;
    Console.WriteLine(str.TestMethod("Hello World!!"));
    ........
}

And here is the IL code.

  IL_0001:  ldsfld     string [mscorlib]System.String::Empty
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldstr      "Hello World!!"
  IL_000d:  call       string StringPooling.ExtendedString::TestMethod(string,
                                                                       string)
  IL_0012:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0017:  nop

As you can see it is just a call of static method. The method is not added to the class, but compiler makes it look like that. And on reflection layer the only difference you can see is that CompilerServices.ExtensionAttribute is added.

这篇关于内部如何实现扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆