How are internal extension methods

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

Is reflection taken into account? Or when you have an extension method, its code is injected into the metadata of the type of the target class with some additional flags, noting that it is an extension method, and then the CLR knows how to handle it?

So what’s going on under the hood?

+5
source share
7 answers

, . , CLR . IL.

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!!"));
    ........
}

IL.

  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

, . , . , , , CompilerServices.ExtensionAttribute.

+6

. , .

+4

, reflection . , static helper function helper class, , .

+2

... . . .NET 3.5 .

+1

- . , Visual Studio, (intellisense). : # : ?

0

static , CompilerServices.ExtensionAttribute, .

0

, - . , "". "" ExtensionAttribute. IL. , . , :

var test = new [] { "Goodbye", "Cruel", "World" };
var result = IEnumerable<string>.Where<string>(test, s => s.Length > 5);

, .

LukeH , , ... .

0

All Articles