C#事件,那空的东西怎么了? [英] C# events, what's with that null thing?

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

问题描述

我真的不明白在引发事件时该null测试是做什么的.

I can't really understand what is this null testing thing for when raising an event.

说我有这个代码.

    class ballClass
{


    public event EventHandler BallInPlay;


    public void onHit()
    {
        if (BallInPlay != null)
        {
            BallInPlay(this, new EventArgs());
        }
        else
        {
            MessageBox.Show("null!");
        }
    }



}

并且即使触发onHit()方法,我也想引发BallInPlay.

and I want to to raise a BallInPlay even when the onHit() method is triggered.

现在它告诉我BallInPlay为null.我应该如何或以什么方式填充"它以使其工作?

right now it shows me that the BallInPlay IS null. how or with what should i "fill" it for it to work?

谢谢!

推荐答案

您需要使用处理程序订阅.例如:

You need to subscribe to the event with a handler. For example:

BallClass ball = new BallClass();
ball.BallInPlay += BallInPlayHandler;
// Now when ball.OnHit is called for whatever reason, BallInPlayHandler
// will get called
...
private void BallInPlayHandler(Object sender, EventArgs e)
{
    // React to the event here
}

有关更多信息,您可能需要阅读我的有关事件和委托的文章.

For more information, you may want to read my article on events and delegates.

请注意,我已经修复了上面BallClassOnHit的大小写-使用标准.NET命名约定使您的代码与周围的代码更好地匹配是一个好主意.对其他人更具可读性.

Note that I've fixed the casing of BallClass and OnHit above - it's a good idea to use the standard .NET naming conventions to make your code fit in better with the code around it, and to make it more readable for others.

需要注意的一件事:您目前所进行的null检查不是线程安全的.最后一个订阅者可以在if之后但在调用之前取消订阅.线程安全的版本为:

One thing to note: the nullity check you've got at the moment isn't thread-safe. The last subscriber could unsubscribe after the if but before the invocation. A thread-safe version would be:

public void OnHit()
{
    EventHandler handler = BallInPlay;
    if (handler != null)
    {
        handler(this, new EventArgs());
    }
    else
    {
        MessageBox.Show("null!");
    }
}

不能保证使用最新的订户(因为不涉及内存障碍),但可以保证 不会由于竞争条件而抛出NullReferenceException.

This wouldn't be guaranteed to use the latest subscribers (as there's no memory barrier involved) but it is guaranteed not to throw a NullReferenceException due to race conditions.

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

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