VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • C#委托之一例看懂泛型委托

以为委托在编程中频繁使用,所以微软为使开发者方便使用委托,省去繁琐的重复定义 。给我们提供了三种定义好的泛型委托,分别是 Action、Func和Predicate。下面分别介绍

Action: 此委托绑定的方法不能有返回值,方法可以有至多16个参数,当然也可以无参数;

Func : 此委托绑定的方法可以有返回值。方法可以有至多16个参数;

Predicate: 此委托返回值为布尔型,方法只能又一个参数;

知道了这三个委托的特点下面我们通过这个例子来进一步熟悉他们的用法。 

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace 委托demo_泛型委托
{
    //泛型委托demo  2022年10月8日21:19:55
    //使用的是系统定义好的 Action,Func,Predicate三个泛型委托。他们各自使用场景如下
 
    class Program
    {  
        static void Main(string[] args)
        {
            //无参数的委托
            Action del1 = new Action(toSayHello);
            del1();
            //有参数的委托
            Action<string> del2 = new Action<string>(toSayAnything);
            del2("我叫lhz");
            //有参数,有返回值的委托
            Func<int ,int,int > del3=new Func<int,int,int>(toAdd);
            Console.WriteLine(toAdd(5, 2));
            //参数只能有一个,且返回值类型为bool型
            Predicate<int> del4=new Predicate<int>(isAdult);
            Console.WriteLine("是否成年:" + del4(13));
 
            Console.ReadKey();
        }
 
        //无参数,无返回值方法
        public static void toSayHello()
        {
            Console.WriteLine("Hello!");
        }
        //有参数,无返回值方法
        public static void toSayAnything(string s)
        {
            Console.WriteLine(s);
        }
        //输入两个整数 进行相加的方法
        public static int toAdd(int a, int b)
        {
            return a + b;
        }
        //输入年龄 判断是否成年的方法
        public static bool isAdult(int age)
        {
            if (age > 18)
                return true;
            else
                return false;
        }
 
    }
}

  总结,前面我们说过委托的四个步骤,因为我们使用的泛型委托是系统自定义好的,所以就省略了 咱们的步骤1:委托的定义

利用三个泛型的特点结合使用场景灵活的选择委托便可以。

出处:https://www.cnblogs.com/arcticfish/p/16770313.html
 


相关教程