C#事件为null [英] C# event is null

查看:611
本文介绍了C#事件为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在一个需要引发和处理自定义事件的项目中……我只是简化了一点代码并得到了这样的东西:

I am just working on a project in which i need to raise and handle a custom event... i just simplified a little bit the code and got something like this:

class Car
{
    public int Speed { get; set; }

    public delegate void SpeedTooHigh(string message);

    public event SpeedTooHigh OnSpeedToHigh;

    public Car(int speed)
    {
        this.Speed = speed;

        if (speed >= 100)
        {
            if (this.OnSpeedToHigh != null)
            {
                this.OnSpeedToHigh("Car has a too high speed !");
            }
        }
    }
}

我正在使用该类的主要类:

and the main class in which i am using this class:

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car(120, "Red", "Renault");

        car.OnSpeedToHigh += OnCarSpeedToHigh;

        Console.WriteLine("Test events");

        Console.ReadKey();
    }

    static void OnCarSpeedToHigh(string message)
    {
        Console.WriteLine(message);
    }
}

当我运行此示例时,似乎所有当Car类中的 OnSpeedToHigh为空时。
而且我不明白为什么,因为我要在主类中创建此类的一个实例并将速度设置为大于100,以便 this.OnSpeedToHigh(汽车速度太高!)叫做。

When i am running this example it seems that all the time the "OnSpeedToHigh" is null in Car class. And i do not understand why since i am creating an instance of this class in main class and set the speed to be greater the 100 so that "this.OnSpeedToHigh("Car has a too high speed !")" to be called.

这足以引发事件,实例化类并将速度设置为大于100的情况吗?

Is this enough for raising the event, to instantiate the class and set the speed to be greater the 100 for example ?

请让我知道这一点。

推荐答案

您正在构造函数中触发该事件,但是您正在

You're firing the event in the constructor, but you're not adding an event handler to the event until after the object is constructed.

由于在触发事件时尚未添加任何事件处理程序,因此在事件创建后才向事件添加事件处理程序。为空。

Since you haven't yet added any event handlers at the time you fire the event, the event is null.

您可能不想在构造函数中触发该事件,或者根本不想使用事件,或者希望该事件是静态的,因此您可以在构造汽车之前添加事件处理程序。

You probably don't want to fire the event in the constructor, you don't want to be using events at all, or you want the event to be static, so that you can add the event handler before the car is constructed.

这篇关于C#事件为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆