开发者

Setting static events to null using reflection

开发者 https://www.devze.com 2023-04-11 10:23 出处:网络
I have the following problem: I got a class with ~100 static events and i want to set all those events to null (removing all delegates) when Disposing.

I have the following problem:

I got a class with ~100 static events and i want to set all those events to null (removing all delegates) when Disposing. Can I do this using reflection? because otherwise it would be a lot to write and hard to keep in sync with changes.

I tried something like this:

foreach (EventInfo eventInfo in GetType().GetEvent开发者_C百科s(BindingFlags.Static | BindingFlags.Public))
     {
        // ?
     }

but i dont know how to set them null. I guess this is not workong with reflection, is their maybee another easy way?

Br, David


The following ought to work:

   foreach (EventInfo eventInfo in GetType().GetEvents(BindingFlags.Static | BindingFlags.Public))
   {
      FieldInfo field = GetType().GetField(eventInfo.Name, BindingFlags.Static | BindingFlags.NonPublic);
      field.SetValue(null, null);             
   }

Provided that there are indeed backing fields for the events of course, otherwise there is no way to "set" them.


You can't "set" events, the only available operations are to add or remove a specific delegate.

You can set the backing field however. Note that there's not necessarily a 1:1 correspondence between events and fields -- WinForms uses a dictionary of delegates to avoid wasting space for events with no handlers.

0

精彩评论

暂无评论...
验证码 换一张
取 消