[英]Equivalent code in managed C++ & C# (Events in VB6)
在VB6中,在ActiveX组件中创建的事件表示如下:
公共事件ProcessingComplete()
并在该ActiveX组件中进行调用,例如:
RaiseEvent处理完成
我正在创建一个托管的C ++ DLL,我想用它做同样的事情。 看起来代表不是我想要的。 我认为更合适的项目是__event声明。 救命?!?
最后,我有一个C#应用程序,我想拥有这样的功能:
MyObject :: ProcessingComplete()<---这是发生“ RaiseEvent”时的调用函数。 {
}
谢谢。
听起来确实像您想要一个活动。 在.NET中,事件只是一个委托,按照约定,该委托具有特殊的签名。 这是在类中声明事件的C#示例:
public class MyObject
{
// ...
public event EventHandler ProcessingComplete;
// ...
}
EventHandler是具有两个参数的委托:
public delegate EventHandler(object sender, EventArgs e);
发送者是引发事件的对象,EventArgs对要传递给事件订阅者的任何信息进行编码。
每个事件都应遵循此约定。 如果您希望传达事件的专门信息,则可以创建自己的派生自EventArgs的类。 为此,.NET定义了一个通用类型的EventHandler委托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;
要订阅事件,请使用+=
运算符。 要取消订阅,请使用-=
运算符。
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)
{
// ...
}
在类内部,要触发事件,可以使用常规语法来调用委托:
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);
}
}
活动和代表。
简介:委托是可以保存对方法的引用的类。 与其他类不同,委托类具有签名,并且它只能保存对与其签名匹配的方法的引用。
简介:.NET编程包括委托和事件的概念,以简化“观察者”或“发布/订阅”设计模式。 多数情况下,您使用事件的方式与标准Win32 API或MFC编程中使用回调函数多年相同。
我想代表们是要走的路。
public delegate void ProcessCompleteEventHandler(object sender, EventArgs e);
在课堂以外的地方定义以上内容。 在你的课堂内
class MySampleClass{
public event ProcessCompleteEventHandler ProcessComplete;
void SomeWork()
{
//Do some work, and when its over...
ProcessComplete.Invoke(this, null);
}
}
在您的主程序中:
MySampleClass obj = new MySampleClass();
obj.ProcessComplete += new ProcessCompleteEventHandler(my_handler);
my_handler应该具有相同的签名...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.