我怎么可以变量方法名称在参数
问题描述:
我尝试在其他方法动态调用方法,但此代码dosn't工作。我该怎么做 ?我怎么可以变量方法名称在参数
#region Form1_Load()
private void Form1_Load(object sender, EventArgs e)
{
Load();
//this line
InitTimer(this.Form1_Load(sender,e));
}
#endregion
#region Timer()
public void InitTimer(dynamic _method)
{
System.Windows.Forms.Timer timer1;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(_method);
timer1.Interval = 5000; // in miliseconds
timer1.Start();
}
#endregion
答
你在找什么是代表。委托本质上是一个方法指针,可以在以后调用。
private void Form1_Load(object sender, EventArgs e)
{
Load();
//this line
InitTimer(() => this.Form1_Load(sender,e));
}
public void InitTimer(Action target)
{
System.Windows.Forms.Timer timer1;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += (sender, e) => target();
timer1.Interval = 5000; // in miliseconds
timer1.Start();
}
答
#region Form1_Load()
private void Form1_Load(object sender, EventArgs e)
{
Load();
//this line
InitTimer(OtherLoad);
}
#endregion
#region Timer()
private void OtherLoad(object sender, EventArgs e)
{...}
public void InitTimer(EventHandler _method)
{
System.Windows.Forms.Timer timer1;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += _method;
timer1.Interval = 5000; // in miliseconds
timer1.Start();
}
#endregion
重要:使你的计时器调用不同的方法,以避免一遍又一遍地把定时器设置(我用“OtherLoad”)!
我编辑了你的标题。请参见“[应的问题包括‘标签’,在他们的头衔?(http://meta.stackexchange.com/questions/19190/)”,这里的共识是“不,他们不应该”。 – 2013-03-13 23:47:40
你收到什么具体错误? – 2013-03-13 23:48:06
看起来你会在这里得到一个无限递归,因为你自己调用了'Form1_Load',并且它会在'InitTimer'之前被评估。 – Lee 2013-03-13 23:49:01