使用强大的反射取消事件的订阅。

来源:互联网 发布:精梳羊绒知乎 编辑:程序博客网 时间:2024/06/17 15:01
 
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();       
    }

}