简体   繁体   English

从另一个方法调用一个方法

[英]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' 'Something'没有重载匹配代表'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 . Tick属性的类型为EventHandler

The signature of EventHandler is: EventHandler的签名是:

public delegate void EventHandler(
    Object sender,
    EventArgs e
)

Which means your Something method must match this signature. 这意味着您的Something方法必须与此签名匹配。 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: DispatcherTimer.Tick事件需要一个带有objectEventArgs参数的处理程序:

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

The signature of Something does not match that specific event. Something的签名与该特定事件不匹配。 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....
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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