You need to implement the addition and removal of accessories in the event, and then check the target list of the delegate or save the targets in the list.
In the add method, you can use the Delegate.GetInvocationList method to get a list of goals already added to the delegate.
Since delegates are defined to compare peers, if they are associated with the same method on the same target, you could probably go through this list and compare, and if you don't find any that compare it, you will add new.
Here is a sample code compiled as a console application:
using System; using System.Linq; namespace DemoApp { public class TestClass { private EventHandler _Test; public event EventHandler Test { add { if (_Test == null || !_Test.GetInvocationList().Contains(value)) _Test += value; } remove { _Test -= value; } } public void OnTest() { if (_Test != null) _Test(this, EventArgs.Empty); } } class Program { static void Main() { TestClass tc = new TestClass(); tc.Test += tc_Test; tc.Test += tc_Test; tc.OnTest(); Console.In.ReadLine(); } static void tc_Test(object sender, EventArgs e) { Console.Out.WriteLine("tc_Test called"); } } }
Output:
tc_Test called
(i.e. only once)
Lasse Vågsæther Karlsen Jun 01 '09 at 22:54 2009-06-01 22:54
source share