简体   繁体   English

C#EventHandler

[英]C# EventHandler

class Program
{
    public delegate void mydel();
    public static event mydel myevent;

    static void del()
    {
        Console.WriteLine("Called in del");

    }

    static void Main(string[] args)
    {
        myevent = del;
        myevent += new EventHandler(del);
        myevent();
        Console.ReadLine();

    }
}

myevent += new Eventhandler(del); This line doesn't work...It generates Error "No overload for 'del' matches delegate 'System.EventHandler' " 该行不起作用...它生成错误“对'del'不重载匹配委托'System.EventHandler'”

Simply add the handler: 只需添加处理程序:

    static void Main(string[] args)
    {
        myevent += del;
        myevent();
        Console.ReadLine();

    }

Your event is not an EventHandler . 您的事件不是EventHandler Your event is of type mydel . 您的事件属于mydel类型。

public delegate void mydel(); // declaring the delegate
public mydel myevent; // declaring an event of type mydel with signature void mydel()

public void del() {...} // this method fit the delegate

// myevent += new EventHandler(del); // myevent is not an EventHandler

the problem is with the lines 问题出在线路上

myevent = del;
myevent += new EventHandler(del);

just remove them and replace the syntex. 只需删除它们并替换syntex。

the right syntex to register to event is: 向事件注册的正确语法是:

myevent += new mydel(del);

or 要么

myevent += del;

but not as you did 但不像你那样

myevent = del;

you should also always check before calling an event that it isn't null. 您还应该始终在调用不为null的事件之前进行检查。

so your code should be: 因此您的代码应为:

class Program
{
    public delegate void mydel();
    public static event mydel myevent;

    static void del()
    {
        Console.WriteLine("Called in del");

    }

    static void Main(string[] args)
    {
        myevent += new mydel(del);

        if(myevent != null)
        {
           myevent();
        }

        Console.ReadLine();

    }
}

to learn more on event and registering read here : 要了解有关事件和注册的更多信息,请在此处阅读:

The += operator is used to add the delegate instance to the invocation list of the event handler in the publisher. + =运算符用于将委托实例添加到发布者中事件处理程序的调用列表中。 Remember, multiple subscribers may register with the event. 请记住,多个订阅者可以注册该事件。 Use the += operator to append the current subscriber to the underlying delegate's invocation list. 使用+ =运算符可将当前订阅者附加到基础委托的调用列表中。

Simplify your code, then it will work like magic! 简化您的代码,然后它将像魔术一样工作!

static void Main(string[] args)
{
   myevent += del;
   myevent();
   Console.ReadLine();
}

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

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