我不知道如果這正是你追求......但在下面的代碼是什麼,我們可以使用Reflection
從包含在ObjectListener
的ObjectRaiser
的實例中刪除處理程序:
namespace ObjectEvents
{
class Program
{
private class ObjectRaiser
{
public event EventHandler PropertyChange;
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
PropertyChange(this, new EventArgs());
}
}
}
private class ObjectListener
{
private ObjectRaiser or;
public ObjectListener(ObjectRaiser or)
{
this.or = or;
or.PropertyChange += new EventHandler(PropertyChange);
}
public void PropertyChange(object sender, EventArgs e)
{
Console.WriteLine("I'm listening!");
}
public void RemoveHandlers()
{
var lfi = or.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach(var fi in lfi)
{
var eh = fi.GetValue(or) as EventHandler;
if (eh != null)
{
foreach (var del in eh.GetInvocationList())
{
foreach (var ev in or.GetType().GetEvents())
{
ev.GetRemoveMethod().Invoke(or, new object[] { del });
}
}
}
}
}
}
static void Main(string[] args)
{
var or = new ObjectRaiser();
var ol = new ObjectListener(or);
//This will raise the event
or.Name = "New Name";
ol.RemoveHandlers();
//This will throw an exception because the event has no handler associated
or.Name = "Weird Name";
Console.ReadLine();
}
}
}
注意:這是一個非常簡單的例子,當然需要對現實世界的使用進行重大修改。
基於這個問題,我認爲我希望刪除某個特定用戶的所有代表,而不是全部。 – cadrell0 2012-02-16 18:22:50