zoukankan      html  css  js  c++  java
  • 针对比具体类型更高层次的抽象编写扩展方法例子

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

      判断集合是否包含元素

    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");
  • 相关阅读:
    人月神话
    Rails 最佳实践
    萧伯纳名言名句大全
    听话,照做,执行,别发挥
    So Good They Can't Ignore You
    谈谈遵守公司作战纪律
    如何让自己有动力去长久地做一件事情
    新架构优化问题总结
    Markdown 入门
    关于代码版本管理的思考和建议
  • 原文地址:https://www.cnblogs.com/darrenji/p/3793848.html
Copyright © 2011-2022 走看看