现在的位置: 首页 > 综合 > 正文

匿名委托可以访问局部变量,而原始的委托则必须利用别的方法才可以做到

2013年07月22日 ⁄ 综合 ⁄ 共 1828字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.