C#委托:Predicate<>、 Func<> 、 Action<>的简单理解

来源:互联网 发布:软件安装许可协议 编辑:程序博客网 时间:2024/05/16 11:56

Predicate

使用前

namespace Read{    public delegate void GetShowMember(int[] num);    class Program    {        public static void Main(string[] args)        {            var arr = new int[] { 1, 2, 3, 4, 65, 4, 3, 2, 25, 15123, 53 };            //使用正常的委托方法  委托是一种类型,需要创建实例            var DelShow = new GetShowMember(ShowMember);            DelShow(arr);            Console.ReadKey();        }       public static bool ShowMember(int[] number)        {            bool ret = false;            Console.WriteLine(string.Join(",", number));            return ret;        }}


使用后:

    

           //Predict 委托表示的方法传入一个类型参数,返回值必须是bool类型;            var DelPredictShow = new Predicate<int[]>(ShowMember );            DelPredictShow(arr);


            //等价于            Predicate<int[]> show = ShowMember;            show(arr);


Func:

使用前


namespace Read{    public delegate int GetMax(int[] num);    class Program    {        public static void Main(string[] args)        {            int[] in1 = { 10, 2, 73, 94, 65, 49, 399, 2, 25, 151, 23, 53 };            var arr = new int[] { 1, 2, 3, 4, 65, 4, 3, 2, 25, 15123, 53 };            //使用委托            var DelGetMax = new GetMax(GetMaxNum);            DelGetMax(arr);            DelGetMax(in1);            Console.ReadKey();        }        public static int GetMaxNum(int[] number)        {            int max = number[0];            foreach (var item in number)            {                if (max < item)                    max = item;            }            Console.WriteLine("Get the Max {0}", max);            return max;        }   }}

使用后

 

         //<int[],int>后面是返回值,前面是参数,参数可以有0~16个,返回值必须有一个            var FuncGetMax = new Func<int[], int>(GetMaxNum );            FuncGetMax(in1);            FuncGetMax(arr);


            //等价于                      Func<int[], int> func = GetMaxNum;            func(in1);            func(arr);


Action使用前

namespace Read{    public delegate void ShowMember(int[] num);    class Program    {        public static void Main(string[] args)        {            int[] in1 = { 10, 2, 73, 94, 65, 49, 399, 2, 25, 151, 23, 53 };            var DelShowMember = new ShowMember(ShowMemberOfNumber);            DelShowMember(in1);            Console.ReadKey();        }        public static void ShowMemberOfNumber(int[] number)        {            Console.WriteLine("Show the member of the array");            Console.WriteLine(string.Join(",", number));        }    }}

使用后:

            //<int[]>为参数,可以有0~16个,没有返回值            var DelActionShow = new Action<int[]>(ShowMemberOfNumber );            DelActionShow(in1);

    //等价于            Action<int[]> action = ShowMemberOfNumber;            action(in1);

阅读全文
0 0
原创粉丝点击