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

  • 相关阅读:
    C#产生不重复随机数
    NT6 HDD Installer(硬盘装系统工具)装系统
    R语言实现 广义加性模型 Generalized Additive Models(GAM) 入门
    matlab小段代码学习
    java连接sql server2005
    python正则表达式
    Ubuntu下安装配置JDK 7
    mysql取代rand()的高效率随机读取方法
    UVA 1335 Beijing Guards
    杂思
  • 原文地址:https://www.cnblogs.com/sinxsoft/p/1296571.html
Copyright © 2011-2022 走看看