如何在内部实施扩展方法?我的意思是当编译器看到扩展方法的声明时以及在调用扩展方法时在运行时发生的情况会发生什么.
是否涉及反思?或者当你有一个扩展方法时,它的代码注入到目标类类型元数据中,并带有一些额外的标志,注意这是一个扩展方法,然后CLR知道如何处理它?
所以一般来说,引擎盖下会发生什么?
正如其他同事已经说过的那样,它只是一种静态的方法.关于编译器,我们可以说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!!"));
........
}
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它只是一个静态方法的调用.该方法未添加到类中,但编译器使其看起来像那样.在反射层上,您可以看到的唯一区别是添加了CompilerServices.ExtensionAttribute.