将事件委托从 c# 转换为 vb.net,调用委托而不是引发事件

Convert event delegate from c# to vb.net, calling the delegate instead of raising the event

我已在网上搜索以找到解决此问题的方法,但我仍然摸不着头脑。这是代码,在 c# 中我试图转换为 vb.net。这是代码:

    internal event EventHandler ShellItemUpdated;

    #region internal interface
    protected virtual TreeNodePath CreateTreeNode(System.Windows.Forms.TreeNodeCollection parentCollection, TreeNodePath parentNode, Tppon.Win32.ShellItem shellItem)
    {
        if (shellItem == null) throw new ArgumentNullException("shellItem");
        //
        TreeNodePath node = CreateTreeNode(parentCollection, parentNode, shellItem.Text, shellItem.Path, !shellItem.IsFolder, shellItem.HasSubfolder, !shellItem.IsFileSystem);
        node.ImageIndex = shellItem.ImageIndex;
        node.SelectedImageIndex = shellItem.SelectedImageIndex;
        node.Tag = shellItem;
        //
        shellItem.ShellItemUpdated += delegate(object sender, EventArgs e)
        {
            node.Text = shellItem.Text;
            node.ImageIndex = shellItem.ImageIndex;
            node.SelectedImageIndex = shellItem.SelectedImageIndex;                
        };
        return node;
    }

当我尝试手动转换它时,我不断收到关于引发事件的错误。所以我使用了网络上的一种转换器工具,它给了我这个:

    Friend Event ShellItemUpdated As EventHandler

    Protected Overridable Function CreateTreeNode(parentCollection As System.Windows.Forms.TreeNodeCollection, parentNode As TreeNodePath, shellItem As Tppon.Win32.ShellItem) As TreeNodePath
    If shellItem Is Nothing Then
      Throw New ArgumentNullException("shellItem")
    End If
    '
    Dim node As TreeNodePath = CreateTreeNode(parentCollection, parentNode, shellItem.Text, shellItem.Path, Not shellItem.IsFolder, shellItem.HasSubfolder, _
    Not shellItem.IsFileSystem)
    node.ImageIndex = shellItem.ImageIndex
    node.SelectedImageIndex = shellItem.SelectedImageIndex
    node.Tag = shellItem
    '
    shellItem.ShellItemUpdated += Sub(sender As Object, e As EventArgs) 
    node.Text = shellItem.Text
    node.ImageIndex = shellItem.ImageIndex
    node.SelectedImageIndex = shellItem.SelectedImageIndex

  End Sub
  Return node
End Function

这显然是不正确的,因为我不是在这里发起活动。我从未在 vb 中使用过委托,所以这对我来说是一个黑洞。

它特别抱怨这一行:

shellItem.ShellItemUpdated += Sub(sender As Object, e As EventArgs) 

并说我需要发起一个活动。但我想打电话给代表,而不是引发事件!看起来整个功能都是乱码。非常感谢那里的一些天才帮助我正确转换这个代码片段...

在您的 C# 代码中,您没有调用委托,而是将事件处理程序附加到 ShellItemUpdated 事件。

VB 相当于添加一个事件处理程序是 AddHandler。假设您需要与 C# 代码中相同的功能,此代码应该有效:

AddHandler shellItem.ShellItemUpdated, Sub(sender As Object, e As EventArgs) 
    node.Text = shellItem.Text
    node.ImageIndex = shellItem.ImageIndex
    node.SelectedImageIndex = shellItem.SelectedImageIndex
End Sub