Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

c# - How extension methods are implemented internally

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...