为什么要委托? 扩张方法三要素

使用委托就是为了解决:怎样才能把方法当做参数传递给另外一个方法

下面是对委托和扩展方法的应用实例,很好的实例,strList调用MyWhere类中MyWhereFun方法

第一个类Programe

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> strList=new List<string>
            {
              "2","4","46","8" 
            };//把 集合中 字符串小于“5” 查询并打印出来
            var i = strList.MyWhereFun(delegate(string j) { return j.CompareTo("5") < 0; });
            //Where方法内部:遍历strList集合,然后,把每个元素传到委托里面执行,如果委托返回turn
            //那么把元素选择出来,最后把所有满足条件的元素一看返回

            foreach(var item in i)
            {
                Console.WriteLine(item);         
            }
            Console.ReadKey();//结果是"2","4","46"
        }
    }
}

第二个类 MyWhere

namespace ConsoleApplication2
{
    /// <summary>
    /// 扩张方法三要素
    /// 1.静态类
    /// 2.静态方法
    /// 3.this关键字
    /// </summary>
   public static class MyWhere
    {
       //特别注意参数中this,谁调用MyWhereFun,this就是谁
        public static List<string> MyWhereFun(this List<string> list,Func<string,bool> funcwhere)
        {
            List<string> result = new List<string>();
            foreach(var item in list)   //遍历list的内容,给item
            {
                if(funcwhere(item)) //如果为true,则执行
                {
                    result.Add(item);
                }
            }
            return result;
        }
    }
}



猜你喜欢

转载自blog.csdn.net/sklzl1571/article/details/80076784
今日推荐