0

我尝试在其他方法中动态调用一个方法,但是这段代码不起作用。我该怎么做 ?

#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
4

2 回答 2

2

您正在寻找的是代表。委托本质上是一个可以稍后调用的方法指针。

    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();
    }
于 2013-03-13T23:48:37.973 回答
0
#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”)以避免一遍又一遍地设置计时器!

于 2013-03-13T23:54:47.260 回答