양식 이벤트를 위해 모든 핸들러를 등록하지 않으려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/287663

  •  08-07-2019
  •  | 
  •  

문제

동일한 양식을 사용하는 2 개의 핸들러가 있습니다. 새 핸들러를 추가하기 전에 핸들러를 제거하려면 어떻게합니까 (C#).

도움이 되었습니까?

해결책

양식 자체에서 작업하는 경우 다음과 같은 작업을 수행 할 수 있어야합니다.

의사 코드 :

Delegate[] events = Form1.SomeEvent.GetInvokationList();

foreach (Delegate d in events)
{
     Form1.SomeEvent -= d;
}

양식 외부에서 Sol.

다른 팁

해당 핸들러가 무엇인지 알고 있다면 += 대신 -= 대신에 구독 한 것과 같은 방식으로 제거하십시오.

취급자가 무엇인지 알지 못하면이를 제거 할 수 없습니다. 이벤트 캡슐화로 인해 한 관심있는 당사자가 이벤트를 관찰 할 때 다른 클래스의 관심사를 막지 못하게합니다.

편집 : 나는 당신이 다른 클래스에서 구현 한 이벤트와 같은 컨트롤에 대해 이야기하고 있다고 가정했습니다. 클래스가 이벤트를 "소유"하는 경우 관련 변수를 NULL로 설정하십시오.

나는이 질문이 다소 늙었다는 것을 알고 있지만, 누군가가 누군가를 도울 것입니다. 약간의 반영으로 모든 클래스의 모든 이벤트 핸들러를 등록 할 수 있습니다.

public static void UnregisterAllEvents(object objectWithEvents)
{
    Type theType = objectWithEvents.GetType();

    //Even though the events are public, the FieldInfo associated with them is private
    foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
    {
        //eventInfo will be null if this is a normal field and not an event.
        System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);
        if (eventInfo != null)
        {
            MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;
            if (multicastDelegate != null)
            {
                foreach (Delegate _delegate in multicastDelegate.GetInvocationList())
                {
                    eventInfo.RemoveEventHandler(objectWithEvents, _delegate);
                }
            }
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top