C # What does 3.0 bring to us (6) -- Expansion Method

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.