Example #1
0
        public void Syntax_InstanceEvent()
        {
            var obj    = new SampleObject();
            var mirror = Mirror.ForObject(obj);

            Assert.AreEqual("InstanceCustomEvent", mirror["InstanceCustomEvent"].MemberInfo.Name);

            // adding/removing null should work event though no handlers will be registered
            mirror["InstanceCustomEvent"].AddHandler((Delegate)null);
            mirror["InstanceCustomEvent"].AddHandler((EventHandler)null);
            mirror["InstanceCustomEvent"].AddHandler((EventHandler <EventArgs>)null);
            mirror["InstanceCustomEvent"].RemoveHandler((Delegate)null);
            mirror["InstanceCustomEvent"].RemoveHandler((EventHandler)null);
            mirror["InstanceCustomEvent"].RemoveHandler((EventHandler <EventArgs>)null);
            Assert.AreEqual(6, obj.instanceCustomEventAddRemoveCount);
            Assert.IsNull(obj.instanceCustomEvent);

            // adding other handlers
            int handled = 0;

            SampleObject.CustomEventHandler nonCoercedHandler = (sender, e) => { handled++; };
            mirror["InstanceCustomEvent"].AddHandler(nonCoercedHandler);
            mirror["InstanceCustomEvent"].AddHandler((sender, e) => { handled++; });             // coerced
            mirror["InstanceCustomEvent"].AddHandler <EventArgs>((sender, e) => { handled++; }); // coerced
            Assert.AreEqual(9, obj.instanceCustomEventAddRemoveCount);
            Assert.IsNotNull(obj.instanceCustomEvent);
            obj.RaiseInstanceCustomEvent();
            Assert.AreEqual(3, handled);

            // remove handler (non-coerced only)
            mirror["InstanceCustomEvent"].RemoveHandler(nonCoercedHandler);
            Assert.AreEqual(10, obj.instanceCustomEventAddRemoveCount);
            Assert.IsNotNull(obj.instanceCustomEvent);
            obj.RaiseInstanceCustomEvent();
            Assert.AreEqual(5, handled);
        }