zoukankan      html  css  js  c++  java
  • 匿名委托可以访问局部变量,而原始的委托则必须利用别的方法才可以做到

     public class Class1
        {
            public void AddSendTextEventHandler(SendTextEventHandler st)
            {
                SendTextEvent += st;
            }
            public event SendTextEventHandler SendTextEvent;

            public void doall()
            {
                SendTextEvent("1");
                //为了让效果看的明显,故方法休眠1秒钟
                System.Threading.Thread.Sleep(1000);
                do1();
                SendTextEvent("2");
                System.Threading.Thread.Sleep(1000);
                do2();
                SendTextEvent("3");
                System.Threading.Thread.Sleep(1000);
                do3();
                SendTextEvent("4");
                System.Threading.Thread.Sleep(1000);
                do4();
            }

            void do1()
            { }

            void do2()
            { }

            void do3()
            { }

            void do4()
            { }
        }

        public delegate void SendTextEventHandler(string text);

      public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                LoadData();        
            }

            void LoadData()
            {
                Class1 c = new Class1();
                //Form2为一个普通窗体类,为局部变量,主要是为了用其Text属性显示SendTextEvent传过来的text
                Form2 f = new Form2();
                f.Show();
                //方法1,通过原始的方法注册委托对象(事件)
                c.SendTextEvent += new SendTextEventHandler(c_SendTextEvent);
                //方法2,利用匿名委托
                c.SendTextEvent += delegate(string text)
                {
                    //注意,f为局部变量,可以在这里操作
                    f.Text = text;           
                };
                c.doall();
            }

            //方法2的原始委托注册方式
            void c_SendTextEvent(string text)
            {
                //注意,如果是这种原始方式,Form2的对象f要通过别的方式如建立全局变量来处理器Text属性
            }
        }

     public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
        }

      static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }

  • 相关阅读:
    HTML、DIV+CSS网页制作中排版混乱的几种常见的情况
    ---------------------------------Javascript零基础到入门
    Bootstrap 框架、插件
    陌陌和请吃饭之类的应用,你要是能玩转,那就厉害了
    冬天去理短发脑门心冷,这时候你需要一顶暖和的棉绒帽子
    我感觉我右手食指要废了,不能双击的赶脚,太伤
    小李子你注定拿不了奥斯卡,谁他么让你长那么帅的
    3月16号的《人生元编程》读者见面会,有人去吗?
    新年要有新气象,额头上留一条杠!
    每日学习笔记12.29.2013
  • 原文地址:https://www.cnblogs.com/sinxsoft/p/1296571.html
Copyright © 2011-2022 走看看