如何在参数中变量为方法名称

时间:2013-03-13 23:45:59

标签: c# winforms c#-4.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

2 个答案:

答案 0 :(得分: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();
    }

答案 1 :(得分: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”),以避免反复设置定时器!