You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#转VB.NET时事件解绑代码转换失败问题求助

VB.NET事件解绑逻辑正确写法(C# -= 运算符对应实现)

问题背景

将C#代码转换为VB.NET时,事件处理相关逻辑转换失败,在线转换工具也无法输出正确结果,核心卡点是无法复现C#中通过-=运算符解绑事件的逻辑。
已完成正确转换的TextBox文本变更事件处理代码如下:

Private Sub TextBoxListViewTextTextChanged(sender As Object, e As EventArgs)
    If _subtitleListViewIndex >= 0 Then
        Dim numberOfNewLines As Integer = textBoxListViewText.Text.Length - textBoxListViewText.Text.Replace(Environment.NewLine, " ").Length
        Utilities.CheckAutoWrap(textBoxListViewText, New KeyEventArgs(Keys.None), numberOfNewLines)
        Dim text As String = textBoxListViewText.Text.TrimEnd()
        _subtitle.Paragraphs(_subtitleListViewIndex).Text = text
        SubtitleListView1.SetText(_subtitleListViewIndex, text)
        _listViewTextUndoIndex = _subtitleListViewIndex
        StartUpdateListSyntaxColoring()
    End If
End Sub

编写InitializeListViewEditBox方法时,错误照搬C#运算符写法的异常代码如下,该写法无法通过编译:

Private Sub InitializeListViewEditBox(ByVal p As Paragraph)
    ' 错误写法:VB不支持-=直接解绑事件,且加括号会变成调用方法而非引用委托
    textBoxListViewText.TextChanged -= TextBoxListViewTextTextChanged()
End Sub

正确实现方式

VB.NET没有C#中+=/-=的事件绑定、解绑运算符,对应逻辑需要通过专用关键字实现:

  • 事件绑定:使用AddHandler关键字,搭配AddressOf指向事件处理方法
  • 事件解绑:使用RemoveHandler关键字,搭配AddressOf指向事件处理方法

注意:事件处理方法名后不能加括号,加括号会被识别为直接调用方法,而非传递方法委托引用。

修正后的可正常运行的代码如下:

Private Sub InitializeListViewEditBox(ByVal p As Paragraph)
    ' 正确解绑TextChanged事件
    RemoveHandler textBoxListViewText.TextChanged, AddressOf TextBoxListViewTextTextChanged

    ' 此处可编写初始化编辑框的其他逻辑,例如赋值文本等
    ' 如果需要在初始化完成后重新绑定事件,使用以下写法即可
    ' AddHandler textBoxListViewText.TextChanged, AddressOf TextBoxListViewTextTextChanged
End Sub

补充说明

如果你在定义事件处理方法时使用了Handles关键字(例如方法声明写为Private Sub TextBoxListViewTextTextChanged(sender As Object, e As EventArgs) Handles textBoxListViewText.TextChanged),则不需要手动绑定/解绑事件,VB会自动完成关联。当前场景属于手动控制事件绑定时机的情况,必须使用RemoveHandler+AddressOf的写法。

内容的提问来源于stack exchange,提问作者vahid Araghi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 05:39:14