简体   繁体   中英

Understanding Events in C#

I'm very new to programming, but I'm pretty sure I've almost got this Events thing down. I just need a few pointers, I guess. I'm trying to create a simple example of an Event, one that simply says "Hello!" every second or so. First I have my "Publisher" class:

 public class Publisher
{
     public delegate void MyEventHandler();
     public event MyEventHandler MyEvent;
     public void MyMethod()
    {
       while (true) { Thread.Sleep(1000); if (MyEvent != null) { MyEvent(); } }
    }
}

Next, I have my "Subscriber" class:

 public class Subscriber
{
     public void Subscribe(Publisher TheObject)
    {
         TheObject.MyEvent += new Publisher.MyEventHandler(SayHello);
    }
     public void SayHello() { Console.WriteLine("Hello!"); }
}

Finally, in my Program:

 public class Program {
 static void Main(string[] args) {     

 var ThePublisher = new Publisher();
 var TheSubscriber = new Subscriber();
 TheSubscriber.Subscribe(ThePublisher);
 ThePublisher.MyEvent();

 }
 }

The compiler says that I have an error though. It put a red line underneath "MyEvent" in "ThePublisher.MyEvent();" in Program. The error says "The event 'NameOfProject.Publisher.MyEvent' can only appear on the left hand side of += or -= (except when used from within the type 'NameOfProject.Publisher')" However, I know that I put in "+=" and nothing else. It is stated in my Subscriber class. What am I missing? What am I doing wrong?

In the last line, you're calling ThePublisher.MyEvent() instead of ThePublisher.MyMethod() , as you probably intended to do.

You may not trigger an event directly from outside the class which defines the event.

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