简体   繁体   English

有人可以解释幕后发生的事情吗?

[英]Can someone explain what is happening behind the scenes?

It's not entirely obvious to me what's happening in this situation. 对我来说,在这种情况下发生的事情并不完全是显而易见的。

I'd expect both functions to be fired. 我希望这两个函数都被触发。

Either the EventHander class is storing the list of functions to fire as an array - and the array is copied to a new one every time something is added/removed - or when the assignment is made, the whole thing is copied to a new "collection" - and not just a reference. 要么EventHander类存储要作为数组触发的函数列表 - 每次添加/删除某些内容时都会将数组复制到新数组中 - 或者在进行赋值时,将整个数据复制到新的集合中“ - 而不仅仅是一个参考。

Somebody please enlighten me :D 有人请赐教:D

Here's a little Linqpad script: 这是一个小的Linqpad脚本:

public class Moop
{
    public EventHandler myEvent;
}

void Main()
{
    var moo = new Moop();
    moo.myEvent += (o, sender) => { "Added to Moop #1".Dump(); };   

    var moo2 = new Moop();

    //Copy the reference, I assume?
    moo2.myEvent = moo.myEvent;

    moo2.myEvent += (o, sender) => { "Added to Moop #2".Dump(); }; 

    //Fire the event on #1
    moo.myEvent(null, null);
}

Event handler lists are delegates, and delegates are immutable -- like strings. 事件处理程序列表是委托,委托是不可变的 - 就像字符串一样。 So you do copy the delegate, and the second event handler gets "added to" the 2nd delegate, not the first. 所以你复制委托,第二个事件处理程序“添加”到第二个委托,而不是第一个委托。

You can find out more about delegates at http://www.c-sharpcorner.com/uploadfile/Ashush/delegates-in-C-Sharp/ 您可以在http://www.c-sharpcorner.com/uploadfile/Ashush/delegates-in-C-Sharp/找到有关代表的更多信息

Good luck! 祝好运!

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

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