委托学习2024年5月15日

说明委托类型,相同的返回值和参数类型;声明完成后把值和参数类型传入;委托声明类型可以生成实例

delegate void 1(string 1)

void 1(string 1){}

用委托来添加函数:无返回值,无参数的1类型生成的实例1,往里面添加函数

delegate void 1(string 1);

        static func l;
        static void 1(string 1)
        {

        }
        static void 2(string 2)
        {

        }
        
         static void Main(string[] args)
        {
         //这里两个函数要加static(静态的)不然需要你通过具体类来引用,委托同理。

            l += 1;
            l += 2;
        }

 点燃委托鞭炮,调用实例引燃:

delegate void 1(string 1);

        static func l;
        static void 1(string 1)
        {
Console.WriteLine("你先输出了名字,参数:"+name);
        }
        static void 2(string 2)
        {
Console.WriteLine("你又输出了主题,参数:"+title);
        }
        
         static void Main(string[] args)
        {
         //这里两个函数要加static(静态的)不然需要你通过具体类来引用,委托同理。

            l += 1;
            l += 2;
            l("一个参数");
            Console.ReadKey();
        }

传入类型为函数也是一样的

        delegate void func(string f);
        static func l;
        static void 1(string 1)
        {
            Console.WriteLine("你先输出了名字,参数:"+1);
        }
        static void 2(string 2)
        {
            Console.WriteLine("你又输出了主题,参数:"+2);
        }
        static void run(func l) { 
            l("一个参数");
        }
         static void Main(string[] args)
        {
            l += 1;
            l += 2;
            run(l);
            Console.ReadKey();
        }

如果使用=号将清空链表,使链表中只剩最后一个等号后的函数。也可以使用-=,来清除对应的函数。这里请大家自行测试。

相同案例解释一下:

        delegate int func(int j,int k);
        static func l;
        static int 1(int x,int y){
            return x + y;
            }
        static int 2(int x, int y) {
            return x * y;
        }
         static void Main(string[] args)
        {
            l += 1;
            l += 2;
            Console.WriteLine(l(4,5));
            Console.ReadKey();
        }

运行以上返回值是20,结果是最后一个函数返回值。如何获取每个函数的返回值,这里写了一个示例:

 delegate int func(int j,int k);
        static func l;
        static int 1(int x,int y){
            return x + y;
            }
        static int 2(int x, int y) {
            return x * y;
        }
         static void Main(string[] args)
        {
            l += 1;
            l += 2;
            foreach(Delegate i in l.GetInvocationList()){
               func k=(func)i;
               Console.WriteLine(k(4,5));
            }
            Console.ReadKey();
        }
  1. 委托是一种类型
  2. 委托是一种类型与返回值相同函数的链表
  3. 委托使用+=,=,-=三个符号操作链表里的函数
  4. 调用委托就会依次调用委托链表里的所有函数
  5. 委托返回值默认是最后一个添加的函数返回值

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值