Talk to Xiaojing to read CLR via C # (09)-Extension Method

Source: Internet
Author: User

For some ready-made classes, if we want to add some new methods to improve functions, but do not want to change the existing encapsulation or use the derived classes, what should we do? Here we can use the extension method.

Love at first sight-Expansion of first Knowledge

Extension MethodThis allows you to "add" methods to an existing type without creating a new derived type, re-compiling, or modifying the original type in other ways.

Let's take a look at the example and have an intuitive understanding. An existing class user:

Public class user
{
String _ name;
Public user (string name)
{
_ Name = Name;
}
Public string name
{
Get {return _ name ;}
Set {This. _ name = value ;}
}
}

Now we want to add a method to display the user information and do not want to modify the user class. Use extension methods

The extension method is a special use. We can define static methods and call them in the target type using the syntax of the instance method. With the preceding definition, when a user instance is used, intelligent sensing is generated and the extension method is prompted.

Call result

User user = NULL; // The instance is null.
User. displayname ();
User = new user ("Xiaojing"); // The instance is not null.
User. displayname ();
Console. Read ();

Ildasm.exe, we can see that after defining the extension method, the extension class will add an extensionattribute tag.

Learn about extensions

How to define an extension method?

    • Defines a static class with unlimited names;
    • Define a static method. The first parameter type is the target type to be extended. to indicate that it is an extension method, add the this keyword to the first parameter.

How does the compilation process identify the sequence?

In the above example, the call statement is user. displayname ();, then the compiler check process:

    • First, check whether the displayname () instance method is defined for the variable type user and its base class. If so, the IlCode;
    • If no static method exists, check whether there is a static method named displayname, the first parameter is user, and the static method with the this keyword in the static class. If yes, the corresponding il code is generated.
    • If it still does not exist, a compilation error will occur.
Positive results code-extended rules
    • The extension method must be declared in a non-generic static class, and the class name is not limited. For example, after the extension class name can be modified, the extension method can be called normally. The extension method must have at least one parameter. The first parameter is of the target extension type and is identified by the this keyword.
    • The static class of the extension method cannot be nested in another class. Definitions like the following will produce compilation errors.

    • Extension methods can be defined in different static classes. Therefore, different static classes may have extension methods of the same name. The Compiler does not know how to call them, so it has to generate a compilation error. For example

At this time, we can't use the syntax of the instance method to call, but can only use the static method syntax to call.

User = new user ("Xiaojing"); // The instance is not null.
Extension. displayname (User );
Extension1.displayname (User );

    • The derived class also inherits the extension method. For example, we define the derived class student:

Public class student: User {}

Its intelligent perception also includes the extension methods of the user class.

Therefore, when defining the extension method, you must pay attention that it cannot be used too much. When too many extension methods are used in the base class, some extra smart sensing may be generated in the derived class.

    • Version issues. If you define a method displayname with the same name to the target extension class one day, the call will overwrite the previous extension method, changing the originalProgram. Therefore, the extension method should be used with caution.

    • Although the syntax of the extension method and the instance method looks the same, there is an important difference between them. Let's look at the call below.

User user = NULL; // The instance is null.
User. displayname ();

When an instance method is called, the object cannot be null and a running error occurs.

In the extension method world, the static method is called, so the instance object that calls it can be null.

    • Extended Interface?

In addition to the Type Extension Method, you can also define the Extension Method for the interface. For example

Call process:

New [] {"AA", "BBB", "CCCC"}. showitems ();
"Cathy". showitems ();
Console. Read ();

Ending is the beginning

The introduction to the extension method here is happy ending. Speaking of this topic,Crane chongtianThe Research on middleware is much deeper. I think it's just a joke. If you are interested, learn his series.C #Great use of extension methods

Good extension methods:

    • Msdn:Extension Method (C #Programming Guide)

Http://msdn.microsoft.com/zh-cn/library/bb383977.aspx

    • Blog Park: crane chongtianC #Great use of extension methods

http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html

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.