0

I'm learning C# from a book, and this code is not compiling. Where is the problem here? The error is on this line: evt.SomeEvent += Handler;

Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

delegate void MyEventHandler();

class MyEvent
{
    public event MyEventHandler SomeEvent;

    public void OnSomeEvent()
    {
        if (SomeEvent != null)
            SomeEvent();
    }
}

class EventDemo
{
    static void Handler()
    {
        Console.WriteLine("Event occurred");
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyEvent evt = new MyEvent();

        evt.SomeEvent += Handler;  **// ERROR ON THIS LINE: HANDLER DOESN'T EXIST**

        evt.OnSomeEvent();
    }
}

It's a slow learning for me in that I feel it is difficult to write my own code, I understand and can read most of it now but, I see it as my biggest challenge to write my own programs.

4

1 回答 1

0

您必须在其中声明Handler为公共EventDemo并正确定义它Program

class EventDemo
{
    public static void Handler()
    {
        Console.WriteLine("Event occurred");
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyEvent evt = new MyEvent();

        evt.SomeEvent += EventDemo.Handler;

        evt.OnSomeEvent();
    }
}
于 2013-10-26T13:15:27.727 回答