C# C.事件斗争

C# C.事件斗争,c#,events,C#,Events,我试着写一个简单的代码,它包含火车停下来或开动时的事件 我的应用程序在说我试图使用空事件时不断崩溃。 课程类别: public delegate void trainHandler(); class Program { static void Main(string[] args) { Train e = new Train(); e.Boxcar += new trainHandler (Message); Console.Wr

我试着写一个简单的代码,它包含火车停下来或开动时的事件 我的应用程序在说我试图使用空事件时不断崩溃。 课程类别:

public delegate void trainHandler();

class Program
{
    static void Main(string[] args)
    {
        Train e = new Train();
        e.Boxcar += new trainHandler (Message);
        Console.WriteLine("Welcome to the train, next stop London!");
        string choice = "";
        do
        {
            Console.WriteLine("D-Drive\nS-Stop\nE-Exit ");
            choice = Console.ReadLine().ToUpper();
            switch (choice)
            {
                case "D":
                    Train q = new Train();
                    q.Driving();
                    break;
                case "S":
                    Train q1 = new Train();
                    q1.Stopping();
                    break; 

            }
        } while (choice != "E");
    }
    static void Message()
    {
        Console.WriteLine("Thanks for riding our train!");
    }
}
新类别:

class Train
{
    public event trainHandler Boxcar;

    public void Driving()
    {
        Console.WriteLine("The train took off!");
        if (Boxcar != null)
        {
            Boxcar(); 
        }

    }
    public void Stopping()
    {
        Console.WriteLine("Train stoped, get down!");
        if (Boxcar != null)
        {
            Boxcar(); 
        }

    }
}
您正在每个case语句中创建一个新序列,这两个语句都没有附加事件处理程序。更改开关以触发在程序开始时创建的第th列上的事件:

switch (choice)
{
    case "D":
        e.Driving();
        break;
    case "S":
        e.Stopping();
        break; 
}
问题是您的e列=新列车;在将事件分配给处理程序的情况下,调用Drive或Stopping的列车实例是否与调用Drive或Stopping的列车实例不同


如果希望调用事件,则需要调用驱动程序或停止e实例,或者为在交换机中创建的新实例分配事件处理程序

在哪一行?您是否尝试放置断点并查看?是的,我尝试过,但仍然无法找到它。我尝试在停止和驾驶方法中使用boxcar事件,但它仍然显示为空事件。实际上,您从未调用将boxcar事件连接到消息的火车对象上的驾驶或停车。另一方面,您通常会将Boxcar分配给一个临时变量,检查该变量是否为null,然后调用临时变量以使其线程安全,尽管这看起来不像这里的问题。哦!我没注意到!非常感谢你!!非常感谢。我没有注意到这一点,对此表示感谢!