使用強大的反射取消事件的訂閱。

 
using System;
using System.Collections;
using System.Reflection;
//Delegate
delegate void UpdateDelegate();

//Subject
class Subject
...{
    
public event UpdateDelegate UpdateHandler;

    
// Methods
    public void Attach(UpdateDelegate ud)
    
...{
        UpdateHandler 
+= ud;
    }


    
public void Detach(UpdateDelegate ud)
    
...{
        UpdateHandler 
-= ud;
    }


    
public void Notify()
    
...{
        Console.WriteLine(
"-------------------------");
        
if (UpdateHandler != null) UpdateHandler();
        Console.WriteLine(
"-------------------------");
    }


}


// "ConcreteObserver"
class Observer
...{
    
// Methods
    public static void Show()
    
...{
        Console.WriteLine(
"Observer got an Notification!");
    }

}


class AnotherObserver
...{
    
// Methods
    public static void Show()
    
...{
        Console.WriteLine(
"AnotherObserver got an Notification!");
    }

}


class Instantce
...{
    
public void Show()
    
...{
        Console.WriteLine(
"Instantce got an Notification!");
    }

}


public class Client
...{
    
public static void Main(string[] args)
    
...{

        Subject a 
= new Subject();
        a.UpdateHandler 
+= new UpdateDelegate(Observer.Show);
        a.UpdateHandler 
+= new UpdateDelegate(AnotherObserver.Show);
        a.UpdateHandler 
+= new UpdateDelegate(AnotherObserver.Show);

        Instantce ins 
= new Instantce();
        a.UpdateHandler 
+= new UpdateDelegate(ins.Show);

        Type t 
= a.GetType();
        FieldInfo eventsPropertyInfo 
= t.GetField("UpdateHandler", BindingFlags.Instance | BindingFlags.NonPublic);
        UpdateDelegate eventHanlderList 
= eventsPropertyInfo.GetValue(a) as UpdateDelegate;

        Delegate[] dl 
= eventHanlderList.GetInvocationList();

        
foreach (Delegate d in dl)
        
...{
            
// look up the contents in Delegate
            Console.WriteLine(d.Method.DeclaringType.ToString() + "." + d.Method.Name);
            
// Detach event handler
            a.Detach((UpdateDelegate)d);
        }

        
        a.Notify();       
    }

}
發佈了58 篇原創文章 · 獲贊 4 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章