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

本文通过一个具体的实例展示了如何使用委托和扩展方法。在`Program`类中,我们创建了一个列表`strList`,并使用扩展方法`MyWhereFun`结合委托筛选出小于"5"的字符串。`MyWhereFun`方法定义在静态类`MyWhere`中,接收一个列表和一个`Func<string, bool>`类型的委托作为参数,委托用于判断元素是否满足条件。这种方法允许将方法作为参数传递,实现灵活的过滤操作。" 113414735,10553459,TypeScript与React结合实战:类型系统与全局属性解析,"['TypeScript', 'React', 'jsx', '编程语言']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

下面是对委托和扩展方法的应用实例,很好的实例,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;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值