类的拓展(Extension Methods)※
扩展方法允许不修改原类的情况下为现有类型添加新方法,是 LINQ 的基础实现机制。
定义※
public static class StringExtensions
{
// 第一个参数用 this 修饰,指向被扩展的类型
public static bool IsEmpty(this string s)
{
return string.IsNullOrWhiteSpace(s);
}
}
// 使用
string name = "";
bool empty = name.IsEmpty(); // 像原生方法一样调用
规则※
- 必须定义在静态类中
- 方法必须静态,第一个参数加
this - 优先调用实例方法(如果类本身已有同名方法)
- 通过命名空间引入才能使用
常见应用※
// 扩展 int
public static int Double(this int n) => n * 2;
// 扩展 IEnumerable
public static T FirstOrDefaultSafe<T>(this IEnumerable<T> src, Func<T,bool> pred)
{
return src.Any() ? src.First(pred) : default;
}