码迷,mamicode.com
首页 > Windows程序 > 详细

C# - 委托的使用

时间:2015-08-30 00:57:54      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

代码:

using System;

namespace Delegate
{
   public class Program
    {
        //声明委托
        public delegate void DelegatePait(string Name);

        //声明方法
        public static void A_Pait(string name)
        {
            Console.WriteLine("使用A打印的名称:{0}", name);
        }
        public static void B_Pait(string name)
        {
            Console.WriteLine("使用B打印的名称:{0}", name);
        }

        //声明一个可以传 递  参数为方法  的方法
        public static void Total_Pait(string name, DelegatePait pait)
        {
            pait(name);
        }

        //调用
        static void Main(string[] args)
        {
            //------- 普通委托的使用,使用自定义的Total委托方法 -------

            //此次调用传递 A_Paint为参数的Total_Pait 方法
            Total_Pait("张三", A_Pait);

            //此次调用传递 B_Pait为参数的 Total_Pait 方法
            Total_Pait("李四", B_Pait);


            //------- 实例化委托,不需要使用自定义的委托方法 -------

            //实例化委托,此时的d1,d2 代表的就是方法 A_Pait,B_Pait。
            DelegatePait d1 = new DelegatePait(A_Pait);
            DelegatePait d2 = new DelegatePait(B_Pait);
            d1("张三");
            d2("李四");

            //------- 将多个方法绑定到委托,并依照绑定次序依次执行 -------

            //可以将多个方法赋给同一个委托,或者叫将多个方法绑定到同一个委托。
            //当调用这个委托的时候,将依次调用其所绑定的方法。
            //委托对象可使用 "+=" 运算符进行合并。只有相同类型的委托可被合并。
            //"-=" 运算符可用于从合并的委托中移除组件委托。
            DelegatePait delegateshow;
            DelegatePait d1 = new DelegatePait(A_Pait);
            DelegatePait d2 = new DelegatePait(B_Pait);
            delegateshow = d1;

            delegateshow += d2;//添加另一个委托对象d2,执行A_Pait,B_Pait方法
            delegateshow("张三");

            //执行过后,从委托列表中移除委托对象d2,只执行A_Pait方法
            delegateshow -= d2;
            delegateshow("张三");

            Console.ReadKey();
        }
    }
}

  

C# - 委托的使用

标签:

原文地址:http://www.cnblogs.com/KTblog/p/4770144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!