我是 Delegates 的新手,正在尝试将以下 C# 代码转换为 Vb.Net。
原始C#代码:
public delegate void delConnectionStatusChanged(EventDrivenTCPClient sender, ConnectionStatus status);
public event delConnectionStatusChanged ConnectionStatusChanged;
private ConnectionStatus _ConStat;
public ConnectionStatus ConnectionState
{
get
{
return _ConStat;
}
private set
{
bool raiseEvent = value != _ConStat;
_ConStat = value;
if (ConnectionStatusChanged != null && raiseEvent)
ConnectionStatusChanged.BeginInvoke(this, _ConStat, new AsyncCallback(cbChangeConnectionStateComplete), this);
}
}
private void cbChangeConnectionStateComplete(IAsyncResult result)
{
var r = result.AsyncState as EventDrivenTCPClient;
if (r == null)
throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a EDTC object");
r.ConnectionStatusChanged.EndInvoke(result);
}
转换为Vb.Net代码:
Public Delegate Sub delConnectionStatusChanged(ByVal sender As EventDrivenTCPClient, ByVal status As ConnectionStatus)
Public Event ConnectionStatusChanged As delConnectionStatusChanged
Private _ConStat As ConnectionStatus
Public Property ConnectionState As ConnectionStatus
Get
Return _ConStat
End Get
Private Set(ByVal value As ConnectionStatus)
Dim [raiseEvent] As Boolean = value <> _ConStat
_ConStat = value
If ConnectionStatusChanged IsNot Nothing AndAlso [raiseEvent] Then ConnectionStatusChanged.BeginInvoke(Me, _ConStat, New AsyncCallback(AddressOf cbChangeConnectionStateComplete), Me)
End Set
End Property
Private Sub cbChangeConnectionStateComplete(ByVal result As IAsyncResult)
Dim r = TryCast(result.AsyncState, EventDrivenTCPClient)
If r Is Nothing Then Throw New InvalidOperationException("Invalid IAsyncResult - Could not interpret as a EDTC object")
r.ConnectionStatusChanged.EndInvoke(result)
End Sub
完整的源代码和转换可以在以下位置查看: https: //pastebin.com/LuvqDvtM
转换后,我收到相同的行错误:
r.ConnectionStatusChanged.EndInvoke(result)
和
ConnectionStatusChanged.BeginInvoke(Me, _ConStat, New AsyncCallback(AddressOf cbChangeConnectionStateComplete), Me)
错误 BC32022“公共事件 ConnectionStatusChanged As EventDrivenTCPClient.delConnectionStatusChanged”是一个事件,无法直接调用。使用“RaiseEvent”语句引发事件。
因此,我了解到该行是一个事件,我可以使用“RaiseEvent”语句来代替,但我不明白该行实际上在做什么,或者“RaiseEvent”的处理程序应该是什么。
C# 事件被视为常规委托,可以被 Invoked 和 BeginInvoked(异步调用处理程序),而 VB.Net 似乎并不容易做到这一点。您可以创建您自己的该委托版本,它不是事件,因此您可以对其进行 BeginInvoke。
委托被异步调用,这只会引发事件。这将允许事件处理程序异步运行,并且仍然调用 EndInvoke 来等待所有处理程序(它们的调用委托)完成。