C #3.0 introduces new features. The extension method can greatly increase the beauty of your code, and the extension method provides your extension. NET Framewoke class extension path, writing and rules are also simple.
There are several requirements for writing extension methods:
First, the class of the extension method must be global and cannot be an internal nested class.
Second, the class of the extension method is static.
Third, the extension method is static.
Fourth: the data type of the first parameter of the extension method must be the extension type.
Fifth: The first parameter of the extension method uses the this keyword.
The following is a simple code:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ExtensionMethod
7 {
8 public static class TestClass
9 {
10 public static void Print(this int i)
11 {
12 Console.WriteLine(i);
13 }
14
15 public static int Times(this int i)
16 {
17 return i * 2;
18 }
19
20 public static int Add(this int i, int d)
21 {
22 return i + d;
23 }
24 }
25
26 class Program
27 {
28 static void Main(string[] args)
29 {
30 int number = 4;
31 number.Print();
32 Console.WriteLine(number.Times());
33 Console.WriteLine(number.Add(5));
34 }
35 }
36 }
The code is very simple. It is extended to the int type.
The first is to define a Print method, which is an extension method without parameters and no return values.
The second is to define an extension method with a return value without parameters.
The third is to define an extension method with parameters that return values.
Sample Code: Download