简体   繁体   English

未引发 C# 事件

[英]C# Events not being raised

So I am trying to learn events and I've done all that's needed to be done to Raise and listen to a simple event, but I am getting no feedback at all when I run the code.所以我正在尝试学习事件,并且我已经完成了所有需要做的事情来引发和收听一个简单的事件,但是当我运行代码时我根本没有得到任何反馈。 The event is simply ignored and only the Hello world is computed.该事件被简单地忽略,只计算 Hello world。 I have two classes, one is a simple Car class, the other an Owner class.我有两个类,一个是简单的 Car 类,另一个是 Owner 类。

In the car class, I create the event and Raise it according to how the documentation by microsoft says.在汽车类中,我创建了事件并根据 microsoft 的文档说明进行了提升。 In the owner class, I listen to it via calling function and then subscribing to it.在所有者类中,我通过调用函数然后订阅它来收听它。 Still, nothing happens.尽管如此,什么也没有发生。 Please help, i'm about to give up on this.请帮忙,我即将放弃这个。

//--------CAR CLASS-----//


using System;

namespace EventsTutorial

{
    public class Car
    {
        public event EventHandler<int> CarOnEvent;

        

        public Car(string name, string colour, int id)
        {
            Name = name;
            Colour = colour;
            IsOn = false;
            Id = id;
            TurnOn(id);
        }

        public string Name { get; set; }
        public string Colour { get; set; }
        public bool IsOn { get; private set; }
        public int Id { get; set; }

        protected virtual void TurnOn(int e)
        {
            EventHandler<int> handler = CarOnEvent;
            handler?.Invoke(this, e);
        }
    }
}
//-----------OWNER CLASS-------------
using System;

namespace EventsTutorial
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(" World!");

            Car mycar = new Car("Toyota", "Black", 1);
            mycar.CarOnEvent += Mycar_CarOnEvent;
            
        }

      

        private static void Mycar_CarOnEvent(object sender, int e)
        {
            Car var = (Car)sender;

            Console.WriteLine("The car {0}, is now on", var.Name);
        }
    }
}

You are calling TurnOn in the Car constructor, before anyone is attached to the event.在将任何人附加到事件之前,您正在Car构造函数中调用TurnOn

You must first attach to the event and then call TurnOn .您必须首先附加到事件,然后调用TurnOn

//New car constructor...
public Car(string name, string colour, int id)
{
    Name = name;
    Colour = colour;
    IsOn = false;
    Id = id;
}

//New TurnOn
protected virtual void TurnOn()
{
    EventHandler<int> handler = CarOnEvent;
    handler?.Invoke(this, this.Id);
}

//New main...
public static void Main(string[] args)
{
    Console.WriteLine(" World!");

    Car mycar = new Car("Toyota", "Black", 1);
    mycar.CarOnEvent += Mycar_CarOnEvent;
    myCar.TurnOn()
}

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

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