使用Extension methods 可以在已有的类型(types)中添加方法(Methods),而无需通过增加一种新的类型或修改已有的类型。
比如说,想要给string类型增加一个PrintStrLength()方法,打印出字符串的长度。使用Extension methods可以不需要去修改string类型而实现这一方法。
"hello".PrintStrLength(); //打印出 length of hello is 5
1 using System; 2 3 namespace ExtensionDemo 4 { 5 using Extensions; 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 "hello".PrintStrLength();
"extension".PrintStrLength(); 11 } 12 } 13 } 14 namespace Extensions 15 { 16 // Extension method must be defined in a non-generic static class 17 static class StrExtensions 18 { 19 public static void PrintStrLength(this string str) 20 { 21 Console.WriteLine($"length of \"{str}\" is {str.Length}"); 22 } 23 } 24 }
上面的Demo的运行结果是
length of "hello" is 5
length of "extension" is 9
注意几点:
- Extension methods 扩展方法必须定义在一个静态类中
- Extension methods 是一种特殊的静态方法,在被扩展的类型调用时要像实例方法一样调用。 ("hello".PrintStrLength();)
- 扩展方法的声明 使用this关键字 后面跟着要操作的对象类型
public static void PrintStrLength(this string str)
- 扩展方法的使用: 使用扩展方法时只需先使用using导入扩展方法所在的名字空间(namespace)。在VS中输入扩展方法时intellisense会提示(extension)
- C#不能扩展静态类(如System.Convert)
LINQ查询就是一种常用的对System.Collections.IEnumerable类型的扩展方法(GroupBy, OrderBy, Average方法)。使用时用 Using System.Linq; 语句导入Linq名字空间。