简体   繁体   中英

Call a method from another method

I have this code:

        public void StartTimer()
        {
            var timer = new DispatcherTimer();
            timer.Tick += Something;
            timer.Interval = new TimeSpan(0, 0, 0, 3);
            timer.Start();

        }

        private async void Something()
        {      
         //code goes here....
        }

The problem is that I get this error:

No overload for 'Something' matches delegate 'System.EventHandler'

My question is probably basic: why I get this error and how can I fix it...

The property Tick is of type EventHandler .

The signature of EventHandler is:

public delegate void EventHandler(
    Object sender,
    EventArgs e
)

Which means your Something method must match this signature. Change it to:

public void Something(Object sender, EventArgs e) { ... }

Alternatively, if you can't change the signature of that method, you can create a new delegate that calls your method.

timer.Tick += (s, e) => Something();

The DispatcherTimer.Tick event expects a handler that takes an object and an EventArgs argument:

private void Something(object o, EventArgs e)
{
    // implementation
}

The signature of Something does not match that specific event. Look into the documentation for that event to see how it's done.

Try This

        public void StartTimer()
        {
            var timer = new DispatcherTimer();
            timer.Tick += Something;
            timer.Interval = new TimeSpan(0, 0, 0, 3);
            timer.Start();

        }

        private async void Something(Object sender, EventArgs e)
        {      
         //code goes here....
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM