C # Extension methods

Source: Internet
Author: User

The purpose of the extension method is to add a method to an existing type, such as the following code, which adds a method of turning into a shape for string strings.

In this way, you can add some other methods to refine the code for many existing types.

The following example shows the definition of an extension method to use.

 classProgram {Static voidMain (string[] args) {Console.Write ("1".            ToInt ());        Console.read (); }    }     Public Static classextendsion { Public Static intToInt ( This stringstr) {            returnConvert.ToInt32 (str); }    }
View Code

Extension method definition Note points:

1. The class where the extension method definition resides must be statically static.

2. The extension method definition must be static.

3. The first parameter of the extension method is the type to be extended, which is placed after the This keyword.

4. The. NET version is 3.0 or 2.0 error (errors below), only 3.5 and later can be used directly

Error 1 could not define a new extension method because the type "System.Runtime.CompilerServices.ExtensionAttribute" required by the compiler could not be found. Is the reference missing?

You can see this http://www.cnblogs.com/TianFang/archive/2008/08/23/1274678.html.

How the extension method works for me:

In short, for convenience.

C # Extension methods

Related Article

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.