在 VB6 中,在 ActiveX 组件中创建的事件是这样表述的:
公共(public)事件处理完成()
并调用该 ActiveX 组件,例如:
RaiseEvent 处理完成
我正在创建一个托管 C++ DLL,我想用它来做同样的事情。看起来代表并不是我想要的。我认为更合适的项目是 __event 声明。帮忙?!?
最后,我有一个 C# 应用程序,我希望它具有这样的功能:
MyObject::ProcessingComplete() <--- 这是在“RaiseEvent”发生时调用的函数。 {
谢谢。
最佳答案
听起来您确实想要举办事件。在 .NET 中,事件只是一个按照约定具有特殊签名的委托(delegate)。下面是在类中声明事件的 C# 示例:
public class MyObject
{
// ...
public event EventHandler ProcessingComplete;
// ...
}
EventHandler 是一个有两个参数的委托(delegate):
public delegate EventHandler(object sender, EventArgs e);
发送者是引发事件的对象,EventArgs 对您要传递给事件订阅者的任何信息进行编码。
每个事件都应遵循此约定。如果您希望为您的事件传达专门的信息,您可以创建您自己的派生自 EventArgs 的类。 .NET 为此目的定义了一个通用类型的 EventHandler 委托(delegate),EventHandler<TEventArgs>
. C# 示例:
class ProcessingCompleteEventArgs : EventArgs
{
public ProcessingCompleteEventArgs(int itemsProcessed)
{
this.ItemsProcessed = itemsProcessed;
}
public int ItemsProcessed
{
get;
private set;
}
}
// ...
// event declaration would look like this:
public event EventHandler<ProcessingCompleteEventArgs> ProcessingComplete;
要订阅事件,请使用 +=
运算符(operator)。要取消订阅,请使用 -=
运营商。
void Start()
{
this.o = new MyObject();
this.o.ProcessingComplete += new EventHandler(this.OnProcessingComplete);
// ...
}
void Stop()
{
this.o.ProcessingComplete -= new EventHandler(this.OnProcessingComplete);
}
void OnProcessingComplete(object sender, EventArgs e)
{
// ...
}
在您的类中,要触发事件,您可以使用普通语法调用委托(delegate):
void Process()
{
// ...
// processing is done, get ready to fire the event
EventHandler processingComplete = this.ProcessingComplete;
// an event with no subscribers is null, so always check!
if (processingComplete != null)
{
processingComplete(this, EventArgs.Empty);
}
}
关于c# - 托管 C++ 和 C# 中的等效代码(VB6 中的事件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1345300/