扩展方法是C#最酷的功能之一。 它允许我们在对象上使用我们的自定义方法,而无需扩展或更改基础类。
扩展方法不过是静态方法。 您可以像调用其他任何静态方法一样直接调用它们。
例
public sealed class User {
public int Id { set ; get ;}
public string Name { set ; get ;}
public int Age { set ; get ;}
public StatusCode Status { set ; get ;}
}
让我们为该类添加一个扩展方法,该方法检查该用户是否处于活动状态。
public static class UserExtensions {
public static bool IsActive ( this User user) {
return user.Status == User.StatusCode.Active;
}
}
...
userObj.IsActive();
...
您可能正在考虑有什么大不了的事,我们可以在User
类本身中添加此方法。 但是,我们可能并不总是拥有对类的控制权。 它可能来自第三方库,我们可能无法扩展该类以添加此方法(因为sealed
)。 那就是扩展方法大放异彩的地方! 这只是一个静态方法,它只能访问对象的公共接口。 但是,它看起来像对象具有方法,并且允许我们以声明的方式编写代码。
扩展方法只是静态方法。 this
关键字与静态方法唯一不同。 您也可以像常规静态方法一样调用它,并且将以相同的方式工作: UserExtensions.IsActive(userObj)
那工具箱呢?
我们著名的Linq
库只不过是扩展方法的集合。 可能我们大多数人都做了以下很多工作。
var list = userList
. Where( i => i .Status == User.StatusCode.Active) ;
我们可以通过添加自己的扩展方法来创建工具箱,因此可以使用新的扩展方法来改进代码。
var list = userList
. Where( i => i .IsActive() );
我们可以通过添加另一种扩展方法来更进一步。
public static IEnumerable<User> OnlyActive( this IEnumerable<User> list) {
return list.Where( i => i.IsActive());
}
现在我们的代码简化为:
userList
.OnlyActive();
我们也可以添加其他方法。
public static IEnumerable<User> OlderThan( this IEnumerable<User> list , int age ) {
return list . Where( i => i .Age > age ) ;
}
public static IEnumerable<User> YoungerThan( this IEnumerable<User> list , int age ) {
return list . Where( i => i .Age < age ) ;
}
public static User GetById( this IEnumerable<User> list , int Id) {
return list . SingleOrDefault( i => i .Id == Id) ;
}
因此我们可以编写如下。 代码不言自明...
userList
.OnlyActive()
.YoungerThan(20);
我们还可以添加更多通用方法。
public static class OtherExtensions {
public static bool IsNull ( this object obj ) {
return obj == null ;
}
public static bool IsNotNull ( this object obj ) {
return !obj.IsNull();
}
public static void IfNotNull<T>( this T obj, Action<T> action){
if (obj.IsNotNull()){
action(obj);
}
}
}
也可以像上一个方法IfNotNull
一样使用泛型。 它期望一个类型为T
的对象,如果它不是null
,它将调用传入的委托函数。
var exists = userList
. GetById(30)
. IsNotNull() ;
userList
. GetById(3)
. IfNotNull( user => Console.WriteLine( user .Name + " found!" ) );
结论
扩展方法是抽象逻辑的好方法。 它的声明性使代码库更简洁易读。
https://dotnetfiddle.net/JGmKGi
From: https://hackernoon.com/building-your-own-toolbox-with-extension-methods-f18q36op