关于撤销事件绑定的问题。
怎么样把绑定上去的事件全部撤销?不能用-=的方法。
using System;
//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()
{
if (UpdateHandler != null) UpdateHandler();
}
}
// "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);
Instantce ins = new Instantce();
a.UpdateHandler += new UpdateDelegate(ins.Show);
a.Notify();
}
}
比如这个事例,怎么把绑定到a.UpdateHandler 上的事件全部撤销?因为在运行时可能有很多对象的方法被绑到上面,并且运行过程中得不到每个对象,或者很难拿到那个对象,所以不能用-=的方式进行撤销绑定,有没有什么办法撤销全部的绑定事件?
或者有什么办法可以看到这个绑定事件里面的内容,比如帮定方法的个数和绑定了什么样的方法
[解决办法]
自己记录一下 绑定了多少 事件在里面?
------解决方案--------------------
可以设置一个列表或集合来记录附加的事件,然后通过索引来访问这些事件.
[解决办法]
帮你看了一下, 下面的代码显示所有事件
static void Main(string[] args)
{
Subject a = new Subject();
a.UpdateHandler += new UpdateDelegate(Observer.Show);
a.UpdateHandler += new UpdateDelegate(AnotherObserver.Show);
Instantce ins = new Instantce();
a.UpdateHandler += new UpdateDelegate(ins.Show);
a.Notify();
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)
{
Console.WriteLine(d.Method.DeclaringType.ToString() + ". " + d.Method.Name);
}
Console.ReadLine();
}
[解决办法]
foreach(Type t in this.SearchItems)
{
S = (SearchBase)t.InvokeMember( " ",BindingFlags.CreateInstance,null,null,new object[]{this.keyWord.Text.Trim()});
S.OnGetEnterpriseInfo += new SearchEventHandler(S_OnGetEnterpriseInfo);
S.OnSearchCompleted += new MethodInvoker(S_OnSearchCompleted);
th = new Thread(new ThreadStart(S.SearchEnterpriseInfo));
这样的咋取消泥??????以前就过,但没结果
th.IsBackground = true;
th.Start();
}