C#转VB.NET委托事件GetInvocationList代码报错求助
C#转VB.NET:事件
GetInvocationList()调用错误的修复方案 在VB.NET中,事件是受保护的特殊成员,不能直接调用事件的GetInvocationList()方法——这就是你遇到「Public Event DisplayText As DisplayTextEvent是事件,无法直接调用,请使用RaiseEvent语句触发事件」错误的核心原因。C#允许直接对事件调用此类方法,但VB.NET有更严格的访问限制,必须先将事件赋值给一个委托变量,再通过变量执行相关操作。
关键修改步骤
- 在
SafeInvokeDisplayText方法中,先创建事件的本地委托副本,既绕过VB的事件访问限制,也能避免多线程场景下的空引用异常 - 通过本地副本调用
GetInvocationList(),而非直接操作原事件 - 异常处理中仍对原事件执行
RemoveHandler操作,移除失效的委托
修正后的完整VB.NET代码
Namespace C.I <Serializable> Public Class DisplayTextEventArgs Public Property Text As String Public Property Duration As TimeSpan Public Sub New(text As String, duration As TimeSpan) Me.Text = text Me.Duration = duration End Sub Public Overrides Function ToString() As String Return String.Format("{0}", Text) End Function End Class <Serializable> Public Delegate Sub DisplayTextEvent(args As DisplayTextEventArgs) Public Class CaptureInterface Inherits MarshalByRefObject Public Event DisplayText As DisplayTextEvent Private Sub SafeInvokeDisplayText(displayTextEventArgs As DisplayTextEventArgs) ' 创建事件的本地副本,绕过VB.NET的事件访问限制 Dim eventCopy As DisplayTextEvent = DisplayText If eventCopy Is Nothing Then Return ' 无监听者 End If Dim listener As DisplayTextEvent = Nothing Dim dels As [Delegate]() = eventCopy.GetInvocationList() For Each del As [Delegate] In dels Try listener = CType(del, DisplayTextEvent) listener.Invoke(displayTextEventArgs) Catch ex As Exception ' 移除无法触发的委托 RemoveHandler DisplayText, listener End Try Next End Sub Public Sub DisplayTextProxyHandler(args As DisplayTextEventArgs) RaiseEvent DisplayText(args) End Sub End Class End Namespace
内容的提问来源于stack exchange,提问作者Michael Clemens
相关产品推荐
相关产品推荐

