簡體   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