简体   繁体   中英

C# Subscribing an Event

I have the following code with 3 different classes. I am trying to Subscribe event from class B to method (event handler) defined in class ControlSystem. All compiles fine, it works no problem but the event handler method is never triggered... What am I doing wrong?

namespace EventTest
{
    public class ControlSystem : CrestronControlSystem
    {
        A myObject = new A();

        public ControlSystem(): base()
        {
            Thread.MaxNumberOfUserThreads = 100;

            // Subscribe Event
            myObject.mySubObject.BEvent += HandleBEvent;

            // Throw Event
            myObject.mySubObject.ThrowEvent();

        }
        public override void InitializeSystem()
        {

        }

        public void HandleBEvent(object sender, EventArgs args)
        {
            Console.WriteLine("Something happend to {0}", sender);
        }
    }

    public class A
    {
        public B mySubObject;

        public A()
        {
            mySubObject = new B();
        }
    }

    public class B
    {
        public EventHandler BEvent;

        public B(){}

        public void ThrowEvent()
        {
            EventHandler handler = BEvent;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }
}

Real code links below (it works with Embeded system so you won't be able to compile it). Idea is to have button press to trigger an event which could alarm other UIs that something happend to it.

http://ideone.com/NJz2Ek

Thanks

You are missing the event keyword.

public event EventHandler BEvent;

is what needs to be there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM