C# delegate v.s. EventHandler

后端 未结 2 1496
遥遥无期
遥遥无期 2021-01-30 12:00

I want to send an alert message to any subscribers when a trap occurred.

The code I created works fine using a delegate method myDelegate del.

My qu

相关标签:
2条回答
  • 2021-01-30 12:03

    It is much better to use an event for your example.

    • An event is understood by the Visual Studio Form and WPF designers, so you can use the IDE to subscribe to events.

    • When raising events, there is no need for you to write your own foreach handling to iterate through them.

    • events are the way that most programmers will expect this functionality to be accessed.

    • If you use a delegate, the consuming code can mess around with it in ways that you will want to prevent (such as resetting its invocation list). events do not allow that to happen.

    As for your second question: Using an event you would create a class derived from EventArgs to hold the data, and pass that to the event when you raise it. The consumer will then have access to it.

    See here for details: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

    0 讨论(0)
  • 2021-01-30 12:11

    The difference between event and delegate is that:

    event declaration adds a layer of protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list, and only allows adding or removing targets from the invocation list

    See What are the differences between delegates and events?

    2) As I see it, your subscriber should not change delegates freely. One subscriber can assign = to it instead of adding +=. This will assign a new delegate, therefore, the previous delegate with its invocation list will be lost and previous subscribers will not be called anymore. So you should use Event for sure. Or you can change your code to make your delegate private and write additional functions for manipulating it to define your own event behavior.

     //preventing direct assignment
     private myDelegate del ;
    
        public void AddCallback(myDelegate m){
            del += m;
        }
    
        public void RemoveCallback(myDelegate m){
            del -= m;
        }
    
        //or
        public static trap operator +(trap x,myDelegate m){
            x.AddCallback(m);
            return x;
        }
        public static trap operator -(trap x, myDelegate m)
        {
            x.RemoveCallback(m);
            return x;
        }
    
    //usage  
    
    //t.AddCallback(new trap.myDelegate(notify));
      t+=new trap.myDelegate(notify);
    
    0 讨论(0)
提交回复
热议问题