委托使用案例



把下面集合中字符串小于"6"的结果查找并打印出来:

1
2
3
List<string> strList = new List<string>() { 
                "3","9","32","7"
};

首先排除掉foreach等做法,我们使用List集合自带的方法实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Linq;

namespace Delegate7
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> strList = new List<string>()
            {
                "3","9","32","7"
            };

            //"Where"方法的内部执行:遍历strList集合,将集合中的每一个元素拿出来,传入委托去执行,
            //如果委托返回true,那就把该元素拿出来,然后把所有符合条件的元素组成新的集合返回。
            var resultList = strList.Where(
                delegate (string s) 
                {
                    return s.CompareTo("6") < 0;
                });

            foreach (var item in resultList)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}

结果:   上面代码中的委托,我们可以使用更简单的lambda表达式编写:

1
var resultList = strList.Where(s => s.CompareTo("6") < 0);

现在我们已经知道了List的Where方法的运行方式,我们可以自己实现一个Where方法,因为该Where方法是标记为可扩展方法的。 MyWhere.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;

namespace Delegate7
{
    public static class MyWhereClass
    {
        /// <summary>
        /// 扩展方法
        /// </summary>
        /// <param name="inputList">也就是调用该扩展方法的集合</param>
        /// <param name="inputDel">传递过来的委托,该委托参数为string类型,返回bool类型</param>
        /// <returns></returns>
        public static List<string> MyWhere(this List<string> inputList,Func<string,bool> inputDel)
        {
            List<string> resultList = new List<string>();
            foreach (var item in inputList)
            {
                //将集合中每一个元素交由该委托执行
                if (inputDel(item))
                {
                    resultList.Add(item);
                }
            }
            return resultList;
        }
    }
}

调用MyWhere方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.Linq;

namespace Delegate7
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> strList = new List<string>()
            {
                "3","9","32","7"
            };
            
            var resultList = strList.MyWhere(s => s.CompareTo("6") < 0);
            foreach (var item in resultList)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}

运行结果:

这个案例很好的体现了委托能够实现的功能,将一个方法当做参数传递,如MyWhere扩展方法那样,在调用的时候将一个方法(lambda表达式)当做参数传递进去,然后由MyWhere方法去调用这个参数(委托)。