简体   繁体   中英

Are Events in C# structs?

So I have a dictionary of EventHandlers, yet I find that when I attach to an event before adding the keyvaluepair to the dictionary, everything works fine. But if I add the keyvaluepair and then update the value of the eventhandler, the dictionary does not update.

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

Delegate types like EventHandler are immutable types. When you use assignment ( = ) or compound assignment ( += ), a new instance is created.

The dictionary holds on to the old instance.

Delegate types are reference types, but the important thing here is their immutability.

When you have an event , the use of the += syntax is not even an assignment. It is an invocation of the add accessor or of the event. It will reassign the backing field (new instance) in a thread-safe way.


Remember that you can author your event accessors yourself. For example:

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>();

With that code, when you go:

TestEvent += GTKWavePipeClient_TestEvent;

your add accessor is called with "implicit" parameter EventHandler value set to GTKWavePipeClient_TestEvent .

Delegates are immutable. You are assigning a new object to TestEvent when invoking += to attach an event. So in your non-working scenario, you have a different object within the Dictionary than the object which has the attached event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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