I'm not sure if this is exactly what you're after ... but in the code below, we can use Reflection
to remove handlers from the instance of the ObjectRaiser
contained in the ObjectListener
:
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();
}
}
}
Note: this is a very simple example and would certainly require significant modifications for real-world use.