-3

我阅读了 MSDN 网站和所有内容,但我找不到关于如何引发接受参数的定时事件的简单解释,该参数可以是 astringdouble. 提供的示例使用ElapsedEventArgs但没有一个显示实现我自己对引发事件的参数的好方法。

我的代码(我没有测试所以可能是错误的):

private double Pressure_Effect(double p, int t){
        time=(double) t;
        v=(((p/(rho*y))-g)*time)/(1.0+(mu*time/(rho*y*x)));
        return v;

    }
    private void Time_Handle(){
        System.Timers.Timer startTimer=new System.Timers.Timer(70);
        startTimer.Elapsed += new ElapsedEventHandler(Activate_Pressure);

    }
    private void Activate_Pressure(object source, ElapsedEventArgs e){
        pressure=2.5;
        double v=Pressure_Effect(pressure, 70);

    }

我想要做的Activate_Pressure是多余的感觉,如果我可以将事件直接传递给Pressure_Effect我不知道如何。我是 C# 新手,所以请多多包涵。我知道我没有启用计时器,并且此代码中可能缺少其他关键部分,但我只是发布它以明确我的问题。

4

2 回答 2

4

所以根据我们的评论线程,我看到这样的事情发生了:

class PressureModel
{
    private double interval = 70;
    private double pressure = 2.5;
    private DateTime startTime;
    private Timer timer;

    // assuming rho, y, g, x, and mu are defined somewhere in here?

    public PressureModel()
    {
        timer = new Timer(interval);
        timer.Elapsed += (sender, args) => PressureEvent(sender, args);
    }

    public void TimerStart() 
    {
        startTime = DateTime.Now;
        timer.Start();
    }

    public void TimerStop()
    {
        timer.Stop();
    }

    private void PressureEvent(object sender, ElapsedEventArgs args)
    {
        // calculate total elapsed time in ms
        double time = (double)((args.SignalTime - startTime).TotalMilliseconds);
        // calculate v
        double v = CalculateV(time);
        //
        ... do you other work here ...
    }

    private double CalculateV(double time)
    {
        double p = this.pressure;
        // not sure where the other variables come from...
        return (((p/(rho*y))-g)*time)/(1.0+(mu*time/(rho*y*x)));
    }
}

我觉得PressureEvent多分开一点也不坏。在给定某些参数的情况下,我仍然会保留一个v自行计算的函数,然后你需要做的任何其他事情也v可以是它自己的方法。

于 2013-08-20T16:08:17.153 回答
2

So you want to ignore some of the arguments passed to the given event handler, and add some additional ones of a fixed value. You have just shown how you can do that; you make a new method of the signature that the Timer's event expects, and then you omits the arguments you don't want and add in some fixed values that you do want. You are correct to think that this is a rather verbose method of accomplishing what you want. There is indeed a more terse syntax. You can use an anonymous method, more specifically a lambda, to do what you want. This is the syntax for that:

startTimer.Elapsed += (s, args) => Pressure_Effect(2.5, startTimer.Interval);
于 2013-08-20T16:18:04.550 回答