简体   繁体   English

C#订阅事件

[英]C# Subscribing an Event

I have the following code with 3 different classes. 我有以下带有3个不同类的代码。 I am trying to Subscribe event from class B to method (event handler) defined in class ControlSystem. 我试图将事件从类B订阅到类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. 想法是按下按钮来触发一个事件,该事件可能会警告其他UI发生了某些事情。

http://ideone.com/NJz2Ek http://ideone.com/NJz2Ek

Thanks 谢谢

You are missing the event keyword. 您缺少事件关键字。

public event EventHandler BEvent;

is what needs to be there. 需要在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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