加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:45:34 所属栏目:百科 来源:网络整理
导读:所以我有一个EventHandlers的字典,但我发现当我在将keyvaluepair添加到字典之前附加到一个事件时,一切正常.但是,如果我添加keyvaluepair然后更新eventhandler的值,则字典不会更新. public static event EventHandler TestEvent;private static Dictionaryint
所以我有一个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这样的委托类型是不可变类型.使用赋值(=)或复合赋值(=)时,将创建一个新实例.

字典保留旧实例.

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

当你有一个事件时,使用=语法甚至不是一个赋值.它是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>();

使用该代码,当你去:

TestEvent += GTKWavePipeClient_TestEvent;

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读