学习委托 代码示例 多播

本文通过一个具体的C#程序示例介绍了委托的基本使用方法,包括如何创建委托类型、实例化委托对象、以及如何实现多播委托的功能。

 

该例子摘自:《C#程序设计教程》--朱毅华等 第132页

 

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
  
        public class WorkerClass
        {

            public int InstanceMethod(int nID, string sName)
            {

                int retval = 0;

                retval = nID * sName.Length;
                Console.WriteLine("调用InstanceMethod方法");
                return retval;
            }


            public static int StaticMethod(int nID, string sName)
            {
                int retval = 0;

                retval = nID * sName.Length + 2;
                Console.WriteLine("调用StaticMethod方法");
                return retval;
            }

            public delegate int SomeDelegate(int nID, string sName); //--参数等必须和要指向的方法一样

             static void Main(string[] args)
             {
                 WorkerClass wr = new WorkerClass();

                 SomeDelegate d1 = new SomeDelegate(wr.InstanceMethod); //--只是挂钩,尚未执行InstanceMethod方法
                 Console.WriteLine("Invoking delegate InstanceMethod, return={0}", d1(5, "aaa"));  //--先调用执行InstanceMethod方法,再执行该Console方法;

                 SomeDelegate d2 = new SomeDelegate(WorkerClass.StaticMethod);

                 Console.WriteLine("Invoking delegate StaticMethod, return={0}", d2(5, "aaa"));
                 Console.WriteLine("...........");
                 Console.WriteLine("测试多播......");

                 SomeDelegate d3 = d2 + d1;  //--按组装的次序来进行调用;先执行d2,再执行d1
                 Console.WriteLine("d1 And d2 return={0}", d3(5, "aaa"));//--按组装的次序来进行调用;先执行d2,再执行d1

                 Console.WriteLine("..................................");

                 int num_method = d3.GetInvocationList().Length;
                 Console.WriteLine("Number of Methods d3:{0}", num_method);

                 d3 = d3 - d2;
                 Console.WriteLine("d3 - d2 return={0}", d3(5, "aaa"));

                 Console.WriteLine("..................................");
                 num_method = d3.GetInvocationList().Length;    //--该委托里还有几个方法;
                 Console.WriteLine("Number of Methods d3:{0}", num_method);

                 Console.ReadKey();
             }

        }


    }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值