简体   繁体   English

C# 事件斗争

[英]C# events struggle

I was trying to write a simple code, which contains events whenever the train stops or drives My application keeps crashing while saying that im trying to use a null Event.我试图编写一个简单的代码,其中包含火车停止或行驶时的事件我的应用程序不断崩溃,同时说我正在尝试使用空事件。 Program Class:程序类:

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!");
    }
}

New Class:新班级:

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(); 
        }

    }
}

You are creating a new train in each of the case statements, neither of which have an event handler attached.您正在每个 case 语句中创建一个序列,它们都没有附加事件处理程序。 change your switch to trigger the event on th train that was created at the start of the program:更改您的开关以触发在程序开始时创建的列车上的事件:

switch (choice)
{
    case "D":
        e.Driving();
        break;
    case "S":
        e.Stopping();
        break; 
}

The problem is that your Train e = new Train();问题是你的Train e = new Train(); where you assign the event to a handler, is a different Train instance to the ones on which you call Drive or Stopping您将事件分配给处理程序的位置与您调用DriveStopping Train实例不同

If you want your event to be called, you need to either call Drive or Stopping on your e instance, or assign an event handler to your new instances you create inside your switch如果您希望调用您的事件,您需要在e实例上调用DriveStopping ,或者为您在switch创建的新实例分配一个事件处理程序

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

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