C#中有关struct在event中注册和删除函数的一个坑

c#中event中删除一个函数时需要注册对象和函数都相同才能删除,而struct会发生值拷贝,所以struct注定不能够删除自身注册的函数,也就是说

struct Test{
  private event Action a;

  public void Regist(){
    //可以成功
    a += TestFunc;
  }
  public void TestFunc(){}
  public void Unregist(){
    //你会发现删不掉了
    a -= TestFunc;
  }
}

这种情况应该使用class代替

posted @ 2025-04-08 23:45  日月久照  阅读(5)  评论(0)    收藏  举报