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());
            }

  • 相关阅读:
    【转】cocos2d-x使用第三方的TTF字体库
    CCControlSlider和CCControlStepper用法
    Cocos2d-x中获取设备语言的方法
    ccrendertexture
    【转】如何使用KeyChain保存和获取UDID
    【luogu P4777】【模板】扩展中国剩余定理(EXCRT)(数论)
    【luogu P1495】【模板】中国剩余定理(CRT)/曹冲养猪(数论)
    【luogu P3980】Volunteer / 志愿者招募(网络流)
    凡喵识图 / Image Recognition(鸽笼原理)(模拟)
    回文树(并查集)(倍增)(LCA)(ST 表)
  • 原文地址:https://www.cnblogs.com/sinxsoft/p/1296571.html
Copyright © 2011-2022 走看看