繁体   English   中英

C#中的事件是否结构化?

[英]Are Events in C# structs?

所以我有一个EventHandlers的字典,但我发现当我在将keyvaluepair添加到字典之前附加到一个事件时,一切正常。 但是,如果我添加keyvaluepair然后更新eventhandler的值,则字典不会更新。

public static event EventHandler TestEvent;
private static Dictionary<int, EventHandler> EventMapping = new Dictionary<int, EventHandler>();

 //TestEvent += GTKWavePipeClient_TestEvent;

  EventMapping.Add(0, TestEvent);
  TestEvent += GTKWavePipeClient_TestEvent;
  //test event is non null now. keyvaluepair in EventMapping has a value of null

EventHandler这样的委托类型是不可变类型。 使用赋值( = )或复合赋值( += )时,将创建一个新实例。

字典保留旧实例。

委托类型是引用类型,但重要的是它们的不变性。

当你有一个event ,使用+=语法甚至不是一个赋值。 它是add accessor或event的调用。 它将以线程安全的方式重新分配支持字段(新实例)。


请记住,您可以自己编写事件访问者。 例如:

public static event EventHandler TestEvent
{
  add
  {
    lock (lockObj)
    {
      EventHandler oldDel;
      if (EventMapping.TryGetValue(0, out oldDel))
        EventMapping[0] = oldDel + value;
      else
        EventMapping.Add(0, value);
    }
  }

  remove
  {
    lock (lockObj)
    {
      EventHandler oldDel;
      if (EventMapping.TryGetValue(0, out oldDel))
        EventMapping[0] = oldDel - value;
    }
  }
}
private static readonly object lockObj = new object();
private static Dictionary<int, EventHandler> EventMapping = new Dictionary<int, EventHandler>();

使用该代码,当你去:

TestEvent += GTKWavePipeClient_TestEvent;

使用“隐式”参数EventHandler value设置为GTKWavePipeClient_TestEvent来调用您的add访问GTKWavePipeClient_TestEvent

代表是不可改变的。 在调用+ =附加事件时,您正在为TestEvent分配新对象。 因此,在非工作场景中,Dictionary中的对象与具有附加事件的对象不同。

暂无
暂无

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

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