针对比具体类型更高层次的抽象编写扩展方法例子

针对某个类型,如果我们不想或不能改变其内部,但想为该类型添加方法,我们可以使用扩展方法来实现。如果该类型有更高层次的抽象,比如接口,我们应为更高层次类型编写扩展方法。另外,扩展方法是链式编程的前提。

 

  判断集合是否包含元素

List<int> list = new List<int>();
if(list != null && list.Count > 0)
{
    
}

我们可以针对比int类型更高层次的ICollection接口写一个扩展方法:

public static bool HasElements(this ICollection list)
{
    return list != null && list.Count > 0
}

然后可以这样使用:

List<int> list = new List<int>();
if(list.HasElements())
{
    
}

 

  判断一个值是否在2个大小数之间

public class A : IComparable{}
public class B : IComparable{}
public class C : IComparable{}

public bool IsBetween(A a, B b, C c)
{
    return a.CompareTo(b) >=0 && c.CompareTo(c) <= 0;
}

我们可以针对比某个具体类更高层次的IComparable接口写一个扩展方法:

public static bool IsBetween<T>(this T value, T min, T max) where T : IComparable<T>
{
    return value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0;
}

可以这样使用:

int a = 10;
a.IsBetween(1,8);

 

  针对集合中的每一个元素实施相同的方法

List<string> strList = new List<string>();
foreach(var item in strList)
{
    SomeMethod(item);
}

首先,可以针对比string更高层次抽象的ICollection编写扩展方法,其次,遍历元素执行的方法抽象成一个委托参数。如下:

public static void EachMethod<T>(this ICollection<T> items, Action<T> action)
{
    foreach(T item in items)
    {
        action(item);
    }
}

现在可以这样使用:

List<string> strList = new List<string>();
strList.EachMethod(s => {
    Console.WriteLine(s);
});

 

  判断元素是否包含在集合中

string str = "a";
List<string> strs = new List<string>(){"a", "b"};
if(strs.Contains(str))
{
    //TODO:
}

可以针对比string更高层次抽象的泛型类型编写扩展方法:

public static bool In<T>(this T source, params T[] list)
{
    if(source == null) throw new ArgumentNulllException("source");
    return list.Contains(source);
}

这样使用:

string temp = "a";
temp.In("a","b");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值