Delegate Array in C#

前端 未结 5 1049
一整个雨季
一整个雨季 2021-02-14 18:10

I am experimenting with calling delegate functions from a delegate array. I\'ve been able to create the array of delegates, but how do I call the delegate?

publ         


        
5条回答
  •  臣服心动
    2021-02-14 18:27

    In .Net, any delegate is in fact actually a "multicast" delegate (it inherits from this built-in base class), and therefore contains an internal linked list which can contain any number of target delegates.

    You can access this list by calling the method GetInvocationList() on the delegate itself. This method returns an array of Delegates...

    The only restriction is that all the delegates inside of a given delegate's linked list must have the same signature, (be of the same delegate type). If you need your collection to be able to contain delegates of disparate types, then you need to construct your own list or collection class.

    But if this is ok, then you can "call" the delegates in a given delegate's invocation list like this:

    public delegate void MessageArrivedHandler(MessageBase msg);
    public class MyClass
    {
         public event MessageArrivedHandler MessageArrivedClientHandler;   
    
         public void CallEachDelegate(MessageBase msg)
         {
              if (MessageArrivedClientHandler == null)
                  return;
              Delegate[] clientList = MessageArrivedClientHandler.GetInvocationList();
              foreach (Delegate d in clientList)
              {
                  if (d is MessageArrivedHandler)
                      (d as MessageArrivedHandler)(msg);
              }
         }
    }
    

提交回复
热议问题