문제

I'm currently passing a EventHandler object to a util function like this:

Timer newTimer(int interval, System.Timers.ElapsedEventHandler handler) {
    ....
    timer.Elapsed += handler;
    ....
}

newTimer(1000, new System.Timers.ElapsedEventHandler(myTimer_Tick));

But this is ugly and forces every caller to create an EventHandler object. How do I change that to something like this?

Timer newTimer(int interval, ref Function handler) {
    ....
    timer.Elapsed += new System.Timers.ElapsedEventHandler(handler);
    ....
}

newTimer(1000, ref myTimer_Tick);
도움이 되었습니까?

해결책

It's not clear why you're using ref here, but if myTimer_Tick has the right signature, you don't need to change your method at all - you can just use:

newTimer(1000, myTimer_Tick);

This uses a method group conversion instead an explicit delegate creation statement. It does the same thing though.

If you want to be able to use parameterless void methods, you could write a helper method to take an Action and wrap that in an ElapsedEventHandler via a lambda expression:

Timer StartTimer(int interval, Action action)
{
    ...
    timer.Elapsed = (sender, args) => action();
    ...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top