简体   繁体   中英

Can a delegate point to more than one method?

Howdy fellow programmers, I am learning about delegates. In my book the author claims that this method will print out the names of the method(s) maintained by a delegate object as well as the name of the class defining the method.

static void DisplayDelegateInfo(Delegate delObj)
{
 foreach (Delegate d in delObj.GetInvocationList())
{
 Console.WriteLine("Method Name: {0}", d.Method);
 Console.WriteLine("Type Name: {0}", d.Target);
}
}

The method is being used in this way.

static void Main(string[] args)
{
 Console.WriteLine("***** Simple Delegate Example *****\n");
 SimpleMath m = new SimpleMath();
 BinaryOp b = new BinaryOp(m.Add);
 DisplayDelegateInfo(b);
 Console.WriteLine("10 + 10 is {0}", b(10, 10));
 Console.ReadLine();
}

My question is, if the DisplayDelegateInfo() loops through the delObj invocation list, in which case would I see more than one item in the array? The book does not seem to give an example of this, can anyone modify the main() method in a way that would display more than one item in this array?

Appreciate any input, Thanks, Leo

static void Main(string[] args)
{
 Console.WriteLine("***** Simple Delegate Example *****\n");
 SimpleMath m = new SimpleMath();
 BinaryOp b = new BinaryOp(m.Add);

 // bellow 'b +=' is short for b = b + 
 b += m.Add1; // Add1 same type (signature really) as method Add

 DisplayDelegateInfo(b);
 Console.WriteLine("10 + 10 is {0}", b(10, 10));
 Console.ReadLine();
}

Copy existing method Add in the body of the class SimpleMath and rename it to Add1 , to make this work. This is called multicast delegate, here is short example of the .NET C# implementation & operations available for it.

Add will remain in the delegate and while Add1 would be appended to the internal list (a FIFO queue) delegates maintain.

A MultiCastDelegate, a class derived from delegate, can hold multiple delegates. The MSDN has a full working example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM