您的位置:首页 > 其它

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

2008-09-23 10:07 288 查看
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());

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐