[英]C# events, how to raise them?
I'm trying to learn raising and handling events in C#. 我正在尝试学习在C#中提升和处理事件。
Here's my simple example: 这是我的简单例子:
/////////////// creating a new BALL object ///
ballClass ball = new ballClass();
void button1_Click(object sender, EventArgs e)
{
// this should make the BALL object raise an event
ball.onHit();
label1.Text = "EVENT SEND";
}
// when event is fired, label text should change
void BallInPlayEvent(object sender, EventArgs e)
{
label2.Text = "EVENT FOUND!";
}
and the ball class: 和球类:
class ballClass
{
public event EventHandler BallInPlay;
public void onHit()
{
this.BallInPlay ///// ??? how should i raise this event?
}
}
In the call I can't really understand, how do I raise the event? 在电话中我无法理解, 我该如何举起活动? Any ideas?... :)
有任何想法吗?... :)
Thanks! 谢谢!
public void onHit()
{
if(BallInPlay != null)
BallInPlay(this, new EventArgs());
}
It's simple, just call the delegate directly, as in 这很简单,只需直接调用委托,就像在
BallInPlay(this, EventArgs.Empty);
The only thing you need to be careful about is a race condition, where BallInPlay is null or set to null before you call it. 您唯一需要注意的是竞争条件,其中BallInPlay为null或在调用之前设置为null。
The pattern to deal with that is 解决这个问题的模式是
var bip = BallInPlay;
if (bip != null)
bip(this, EventArgs.Empty);
Usually, to avoid testing the handler every time (as Ed Guiness showed), it is (IMHO) easier to simply initialize the event with an empty delegate, and then call it without checking: 通常,为了避免每次测试处理程序(如Ed Guiness所示),(IMHO)更容易使用空委托简单地初始化事件,然后调用它而不检查:
class Ball
{
// add an empty delegate to our handler
public event EventHandler BallInPlay = delegate { };
protected virtual void OnHit(EventArgs e)
{
// no need to check, we have at least one
// dummy delegate in the invocation list
BallInPlay (this, e);
}
}
Actually (although Jon Skeet will probably tell you this before I finish writing this post :), the only truly thread safe event call is the one discussed by in Jon Skeet's article . 实际上(尽管Jon Skeet可能会在我写完这篇文章之前告诉你),唯一真正的线程安全事件调用是在Jon Skeet的文章中讨论过的 。
Another important thing you should note is that classes shouldn't really fire events which reside in other classes (ie OnHit
method should not be public
). 您应该注意的另一个重要事项是,类不应该真正触发驻留在其他类中的事件(即
OnHit
方法不应该是public
)。 If a class has a public event (like your BallClass
), it alone should be the one to fire this event. 如果一个类有一个公共事件(比如你的
BallClass
),它就应该是一个触发这个事件的事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.