扩展方法
this 扩展方法、为已有类型添加方法、LINQ 即扩展方法
扩展方法
扩展方法让你在不修改原类型的情况下,给它"添加"新方法。LINQ 的 .Where()、.Select() 全部是扩展方法。
学完本章你将: 掌握 this 扩展方法、为已有类型加方法。
定义扩展方法
csharp
// 必须在静态类中,第一个参数加 this
public static class StringExtensions
{
// 为 string 添加扩展方法
public static bool IsNullOrEmpty(this string? value)
=> string.IsNullOrEmpty(value);
public static string Truncate(this string value, int maxLength)
=> value.Length <= maxLength
? value
: value[..maxLength] + "...";
// 为 int 添加扩展方法
public static bool IsEven(this int n) => n % 2 == 0;
}
// 使用——和实例方法完全一样
string s = "Hello World";
Console.WriteLine(s.Truncate(5)); // "Hello..."
Console.WriteLine(42.IsEven()); // true
扩展方法的工作原理
csharp
// 扩展方法调用
"hello".Truncate(3);
// 编译后等价于
StringExtensions.Truncate("hello", 3);
// 这就是为什么:
// 1. 扩展方法必须在静态类中
// 2. 它们不能访问私有成员
// 3. 实例方法优先级高于扩展方法
LINQ 即扩展方法
csharp
using System.Linq; // 引入扩展方法
// 这些 .Where .Select 都是 IEnumerable<T> 的扩展方法
var result = new[] { 1, 2, 3, 4, 5 }
.Where(n => n % 2 == 0)
.Select(n => n * 10);
// 不 using System.Linq 这些方法不可用