[英]How to expose an event in a c# class?
I am building a simple class to hold related methods. 我正在构建一个简单的类来容纳相关方法。 Part of this code includes synchronising to a database.
此代码的一部分包括同步到数据库。 The built in
SyncOrchestrator
class includes a SessionProgress event handler which I can wire up an event to. 内置的
SyncOrchestrator
类包含一个SessionProgress事件处理程序,我可以将一个事件连接到该事件处理程序。
What I would like to do is instance my class and then hook up an some code to this event so that I can display a progress bar (ill be using BGWorker). 我想做的是实例化我的类,然后将一些代码连接到该事件,以便我可以显示进度条(不使用BGWorker)。
So, my question is probably c# 101, but how do I expose this event through my class the correct way so that I can wire it up? 因此,我的问题可能是c#101,但是如何以正确的方式通过班级公开此事件,以便进行连接?
Thanks 谢谢
I think you're looking for something like this: 我认为您正在寻找这样的东西:
(I also suggest you read the Events tutorial on MSDN .) (我还建议您阅读MSDN上的“ 事件”教程 。)
public class SyncOrchestrator
{
// ...
public event EventHandler<MyEventArgs> SessionProgress;
protected virtual void OnSessionProgress(MyEventArgs e)
{
// Note the use of a temporary variable here to make the event raisin
// thread-safe; may or may not be necessary in your case.
var evt = this.SessionProgress;
if (evt != null)
evt (this, e);
}
// ...
}
where the MyEventArgs
type is derived from the EventArgs
base type and contains your progress information. MyEventArgs
类型是从EventArgs
基本类型派生的,其中包含您的进度信息。
You raise the event from within the class by calling OnSessionProgress(...)
. 您可以通过调用
OnSessionProgress(...)
从类中引发事件。
Register your event handler in any consumer class by doing: 通过执行以下操作,在任何使用者类中注册事件处理程序:
// myMethodDelegate can just be the name of a method of appropiate signature,
// since C# 2.0 does auto-conversion to the delegate.
foo.SessionProgress += myMethodDelegate;
Similarly, use -=
to unregister the event; 同样,使用
-=
取消注册该事件; often not explicitly required. 通常没有明确要求。
Like this: 像这样:
public event EventHandlerDelegate EventName;
EventHandlerDelegate
should obviously be the name of a delegate type that you expect people to provide to the event handler like so: 很明显,
EventHandlerDelegate
应该是您希望人们提供给事件处理程序的委托类型的名称,如下所示:
anObject.EventName += new EventHandlerDelegate(SomeMethod);
When calling the event, make sure you use this pattern: 调用事件时,请确保使用以下模式:
var h = EventName;
if (h != null)
h(...);
Otherwise you risk the event handler becoming null
in between your test and actually calling the event. 否则,您可能会在测试和实际调用事件之间使事件处理程序变为
null
。
Also, see the official documentation on MSDN . 另外,请参阅MSDN上的官方文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.