C# 清除事件繫結的函式

衣舞晨風發表於2015-12-09

原文地址:點選開啟連結

  #region 清除事件繫結的函式
        /// <summary>
        /// 清除事件繫結的函式
        /// </summary>
        /// <param name="objectHasEvents">擁有事件的例項</param>
        /// <param name="eventName">事件名稱</param>
        public static void ClearAllEvents(object objectHasEvents, string eventName)
        {
            if (objectHasEvents == null)
            {
                return;
            }
            try
            {
                EventInfo[] events = objectHasEvents.GetType().GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                if (events == null || events.Length < 1)
                {
                    return;
                }
                for (int i = 0; i < events.Length; i++)
                {
                    EventInfo ei = events[i];
                    if (ei.Name == eventName)
                    {
                        FieldInfo fi = ei.DeclaringType.GetField(eventName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                        if (fi != null)
                        {
                            fi.SetValue(objectHasEvents, null);
                        }
                        break;
                    }
                }
            }
            catch
            {
            }
        }
        #endregion


相關文章