我正在创建一个新类,以便可以使System.Timers.Timer类适合我的需求。我像这样创建我的新班级...

using System.Timers;

class BtElapsedEventArgs : ElapsedEventArgs
{
    //My extras
}

namespace MyGreatNewTimer
{
    class BetterTimer : Timer
    {

    }
}


现在,我只想替换在其他地方触发的Elapsed事件。

private void TestTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  //Timer has elapsed
}


我希望它产生以下...

private void TestTimer_Elapsed(object sender, BtElapsedEventArgs e)
{
  //Timer has elapsed
}


我该怎么做呢?

最佳答案

如果我正确理解您的问题,则可以遵循How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide)并创建自己的Elapsed事件并隐藏原始的Epalsed事件:

namespace MyGreatNewTimer
{
    class BtElapsedEventArgs : EventArgs
    {
        public DateTime SignalTime { get; set; }
        //Some other properties
    }
    class BetterTimer : Timer
    {

        new public event EventHandler<BtElapsedEventArgs> Elapsed;

        public BetterTimer()
        {
            base.Elapsed += BetterTimer_Elapsed;
        }

        void BetterTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var handler = this.Elapsed;
            if(handler!=null)
            {
                var bte = new BtElapsedEventArgs() { SignalTime = e.SignalTime};
                //Set other properties, then fire the event
                handler(sender, bte);
            }
        }
    }
}

08-26 19:04