简体   繁体   English

如何限制委托方法的数量?

[英]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. 我有一位delegate ,我只希望可以注册5次。 I know i can set the delegate private and write a AddRegister() method to control the amount of registered method. 我知道我可以将delegate设置为private并编写AddRegister()方法来控制已registered方法的数量。 Have any other ideas ? 还有其他想法吗?

You can use GetInvocationList method on the delegate object and then call Count method on it. 您可以在委托对象上使用GetInvocationList方法,然后在其上调用Count方法。 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. 这样,无论在什么地方注册,都不必写count <= 5条件。 Hence it will be easier to maintain. 因此,它将更易于维护。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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