C#2.0技术探讨(1):匿名方法
/*--===------------------------------------------===---
匿名方法: 通过+= 后面跟delegate{}; 以内联方式编码
匿名方法是.NET2.0特有的,而不是1.1具有的(给学员演示的时候要注意)
许明会 2007年12月10日 23:35:30
--===------------------------------------------===---*/
using System;
using System.Windows.Forms;
namespace xumh
{
public class myClass:Form
{
private Button btnHello;
private Label lblTime;
private Timer tmr;
public myClass()
{
btnHello = new Button();
btnHello.Text = "问好";
btnHello.Click += delegate{ //测试匿名方法
MessageBox.Show("Yes,It's Anonymouse method!");
};
btnHello.Location = new System.Drawing.Point(100,80);
this.Controls.Add(btnHello);
//lblTime
lblTime = new Label();
lblTime.Location = new System.Drawing.Point(100,120);
lblTime.Size = new System.Drawing.Size(140,20);
this.Controls.Add(lblTime);
//tmr
tmr = new Timer();
tmr.Enabled = true;
tmr.Interval = 1000;
tmr.Tick += delegate{ //测试匿名方法
lblTime.Text = DateTime.Now.ToString();
};
//带参数的匿名方法
this.MouseMove += delegate(object Sender,MouseEventArgs e){
this.Text = string.Format("({0},{1})",e.X,e.Y);
this.Opacity = double.Parse( e.X.ToString()) /this.Width;
};
}
};
public class runMyApp
{
static void Main()
{
Application.Run(new myClass());
}
};
}
匿名方法: 通过+= 后面跟delegate{}; 以内联方式编码
匿名方法是.NET2.0特有的,而不是1.1具有的(给学员演示的时候要注意)
许明会 2007年12月10日 23:35:30
--===------------------------------------------===---*/
using System;
using System.Windows.Forms;
namespace xumh
{
public class myClass:Form
{
private Button btnHello;
private Label lblTime;
private Timer tmr;
public myClass()
{
btnHello = new Button();
btnHello.Text = "问好";
btnHello.Click += delegate{ //测试匿名方法
MessageBox.Show("Yes,It's Anonymouse method!");
};
btnHello.Location = new System.Drawing.Point(100,80);
this.Controls.Add(btnHello);
//lblTime
lblTime = new Label();
lblTime.Location = new System.Drawing.Point(100,120);
lblTime.Size = new System.Drawing.Size(140,20);
this.Controls.Add(lblTime);
//tmr
tmr = new Timer();
tmr.Enabled = true;
tmr.Interval = 1000;
tmr.Tick += delegate{ //测试匿名方法
lblTime.Text = DateTime.Now.ToString();
};
//带参数的匿名方法
this.MouseMove += delegate(object Sender,MouseEventArgs e){
this.Text = string.Format("({0},{1})",e.X,e.Y);
this.Opacity = double.Parse( e.X.ToString()) /this.Width;
};
}
};
public class runMyApp
{
static void Main()
{
Application.Run(new myClass());
}
};
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步