How can I use the following events/delgates, written in C#, in VB.NET?

我与影子孤独终老i 提交于 2019-12-04 05:17:35

问题


I'm using JdSoft's APNS-Sharp library in my ASP.NET web app. The library is written in C#, and makes extensive use of Delegate Functions and Events for threading purposes. My application is written in VB.NET, and I'm a little confused on about how to translate the following sample code (C#):

....
//Wireup the events
service.Error += new FeedbackService.OnError(service_Error);
....
}

static void service_Error(object sender, Exception ex)
{
Console.WriteLine(...);
}

Here are the relevant members of the FeedbackService class:

public delegate void OnError(object sender, Exception ex);
public event OnError Error;

Basically, I'm trying to figure out how to attach a function (like service_Error) to an event (like Error) in VB.NET. I'm unclear on what the += syntax means in this context, and VisualStudio says that the 'Error' event cannot be accessed directly by my VB.NET code for some reason.

Thanks!


回答1:


The += operator is basically subscribing the FeedbackService.OnError function to the Error invocation list. So when the Error event is raised, the OnError method is invoked.

To translate the above code to VB.NET, it would look something like:

// define delelgate/event
Public Delegate Sub OnError(sender As Object, ex As Exception)
Public Event OnError Error

// attach method to event
AddHandler service.Error, service_Error

See How to: Raise and Consume Events for some examples in VB.NET.




回答2:


AddHandler service.Error, service_Error



回答3:


I'm not sure on the VB implementation I'm afraid, but the += syntax in C# with respect to delegates, adds a method to the delegates list of methods (invocation list)



来源:https://stackoverflow.com/questions/7636382/how-can-i-use-the-following-events-delgates-written-in-c-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!