LINQ learning notes (4) Extension Method

Source: Internet
Author: User

The content to be summarized today is the latest feature of C #3.0-the extension method, which is used in a lot of LINQ queries, so it is necessary to summarize, so that we can better master the LINQ. The following describes the extension methods.

1. What is an extension method?

The extension method is to add a method in addition to the method declared by the class itself. When called, it is called as an instance member of the class. This is an extension method.

2. Why declare the extension method? What is the role of the extension method?

This type can be extended by function without modifying the type definition.

3. How do I declare an extension method?

For example:

1 class mydata
2 {
3 private double D1, D2, D3; // declare the variable
4
5 Public mydata (double D1, double D2, double D3) // constructor. Class Object.
6 {
7 d1 = D1; // initialize the variable D1.
8 D2 = d2;
9 D3 = D3;
10}
11
12 public double sum () // declaration method
13 {
14 return D1 + D2 + D3;
15}
16}
17
18 static class extendmydata
19 {
20 public static double average (this mydata MD) // keyword this, the method declaration is static.
21 {
22 return Md. sum ()/3;
23}
24}
25
26 class Program
27 {
28 static void main (string [] ARGs)
29 {
30 mydata MD = new mydata (3, 4, 5); // create a class object.
31
32 console. writeline ("sum: {0}", MD. sum (); // call the instance method
33 console. writeline ("average: {0}", MD. Average (); // call the Extension Method
34 console. readkey ();
35}
36}
37 // program output result: sum: 12
38 // average: 4

4. What are precautions for declaring the extension method?

1> both the extension method and the class of the extension method must be declared as static.

2> the extension method must contain keywords as its first parameter type and follow the name of the extended class.

The above is part of the extended method summarized today. The time for this evening is sufficient. Next we will summarize the query syntax and method syntax.

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.