This syntax can appear in C #3.0.
Int I = 2;
Console. writeline (I. Square ());
This is the extension method.
How can we use the square method for an int?
You only need to define such a function
Public static int square (this int I)
{
Return I * I;
}
This indicates that the meaning of this for int instances is the same as that for the indexer. Int indicates that the int type is extended.
However, this extension function has certain limitations.
1. The extension method must be static.
2. The extension method must be defined on top-level static classes.
Let's take a look at the Il implementation.
. Method public hidebysig static int32 square (int32 I) di-managed
{
. Custom instance void [system. Core] system. runtime. compilerservices. extensionattribute:. ctor () = (01 00 00 00)
// Code size 9 (0x9)
. Maxstack 2
. Locals Init ([0] int32 CS $1 $0000)
Il_0000: NOP
Il_0001: ldarg.0
Il_0002: ldarg.0
Il_0003: MUL
Il_0004: stloc.0
Il_0005: Br. s il_0007
Il_0007: ldloc.0
Il_0008: Ret
} // End of method myextention: Square
C # The Compiler generates myextention. Square (int32 I) and does not change the int type. We can use it as the visitor mode, but it is essentially different from the visitor mode.