+= operator with Events

后端 未结 6 954
离开以前
离开以前 2020-11-28 09:50
public void Bar()
{
    Foo foo = new Foo();
    **foo.MyEvent += foo_MyEvent;**
    foo.FireEvent();        
}

void foo_MyEvent(object sender, EventArgs e)
{
    (         


        
6条回答
  •  遥遥无期
    2020-11-28 10:37

    Event is just the immutable list of delegates (i.e. subscribes which will get called when something publishes/invokes that event). You could argue that we could have used List instead. If we went that way, someone could have tempered with our subscribers.

    In above scenario where you use List, you could do:

    lstDelegate = newDelegate

    and you have wiped existing subscribers (lstDelegate only contains ur delegate callback now).

    To stop that behaivour we have Event. When you use event, complier wont allow you do that, you are only allowed to add/remove your own delegate by using += and -=. That's how I try to differentiate it anyway. hope it helps.

提交回复
热议问题