c#中的扩展方法的使用

扩展方法必须是静态的方法,并且扩展方法必须定义在静态的类中。但是不是通过静态类名.静态方法的形式调用该扩展方法。而是像类的实例调用类中的成员方法一样去调用扩展方法。和类中的实例方法的调用形式是一样的。并且扩展方法只能有实例调用,业就是说目标类不能是静态类使用格式如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ExtendsMethod
 7 {
 8     class ExtendsMethod
 9     {
10         static void Main(string[] args)
11         {
12             string world = "my name is liuzhiqiang";
13             Console.WriteLine(world.Count());
14             Console.WriteLine(world.ToString());
15         }
16     }
17     public static class StringExtends
18     {
19         /// <summary>
20         /// string类的扩展方法Count()用于计算字符串中单词的个数
21         /// </summary>
22         /// <param name="str">传递形参</param>
23         /// <returns></returns>
24         public static int Count(this string str)
25         {
26             
27             return str.Split(new char[] { ' ', ',', '?', '.' }, StringSplitOptions.RemoveEmptyEntries).Length;
28         }
29         /// <summary>
30         /// 和string类的tostring()函数同名所以自定义的的扩展功能函数永远不会被执行
31         /// </summary>
32         /// <param name="str"></param>
33         /// <returns></returns>
34         public static string ToString(this string str)
35         {
36             return "my tostring()";
37         }
38     }
39 }

扩展方法在泛型类中叶可以使用,目的是扩展泛型类的功能,使用格式类似于非泛型类。使用格式如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace FXExtendsMethod
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Printer<string> printer = new Printer<string>("hello world!");
13             printer.PrinttExMethod();
14         }
15     }
16     public class Printer<T>
17     {
18         public T CurrentMsg
19         {
20             get;
21             set;
22         }
23         public Printer(T data)
24         {
25             CurrentMsg = data;
26         }
27         public void Print(T msg)
28         {
29             Console.WriteLine(msg);
30         }
31  
32     }
33     public static class PrinterEX
34     {
35         /// <summary>
36         /// 泛型类中的扩展方法的使用和非泛型类中的扩展方法使用形式基本相同
37         /// </summary>
38         /// <typeparam name="T"></typeparam>
39         /// <param name="printer"></param>
40         public static void PrinttExMethod<T>(this Printer<T> printer)
41         {
42             T msg = printer.CurrentMsg;
43             Console.WriteLine(msg);
44         }
45     }
46 }
原文地址:https://www.cnblogs.com/moonfans/p/2804548.html