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.