简体   繁体   中英

How to limit the amount of method for a delegate?

I have a delegate ,and i want it only can be register for 5 times. I know i can set the delegate private and write a AddRegister() method to control the amount of registered method. Have any other ideas ?

You can use GetInvocationList method on the delegate object and then call Count method on it. Something to the effect of the following

Mydel d1 = this.MyMethod;
int count = d1.GetInvocationList().Count();//Here count will be 1

Also I would prefer to have the registration combined with the above functionality in one place similar to the one you mentioned in your question. In this way you need not have to write the count <= 5 condition wherever it is being registered. Hence it will be easier to maintain.

Hope this helps.

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