退订事件的最有效方式

时间:2019-05-25 14:25:06

标签: c# events

我有一个添加到事件的脚本列表,这些脚本是对象(类)的列表,添加它们时,将调用一个名为AddObject的函数。然后订阅脚本,并调用与该订阅对应的方法。然后,我想制作一个名为RemoveObject的函数,它的功能与之相反。简介:取消订阅大型活动的最有效方式是什么

事件:

    private List<object> Scripts = new List<object>(); // Does some stuff to add scripts if method was found (and also subscribes it to an event)
    private delegate void AllCallA();
    private event AllCallA CallA;
    public void RemoveObject(object obj)
    {
        // Scripts is just a list of objects
        Type type = obj.GetType();
        Delegate[] getA = CallA.GetInvocationList();

        MethodInfo[] Methods = {
            type.GetMethod("CallEventA", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance),
            // etc
        );

        for (int i = 0; i < Scripts.Count; i++)
        {
            if (Scripts[i] == obj) // Check if current script is equal to the object we want to remove
            {
                if (Methods[0] != null && getA.Length > 0) // check if method is not null and event list is greater than 0
                    if (getA.Length >= i) // Check if calla length is less than this current iteration
                        CallA -= (getA[i] as AllCallA); // somehow unsubscribe to this event using iteration? (or object..?)
                // etc
            }
        }

        /* AddObject is less advanced, just basically does this (pseudo code,):
         * MethodInfo[] methods = { mymethodname };
         * if (methods[0] is not null and its params length is equal to 0) then do
         *     CallA += () => methods[0].Invoke(obj, null);
         * end
         */
    }

我尝试过这种方法,但是被调用的方法似乎没有停止

0 个答案:

没有答案