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

时间:2016-02-04 04:54:42

标签: c# asp.net vb.net delegates event-handling

我已经在网上搜索了一个解决方案,但是我还在挠头。这是代码,在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) 

并说我需要举办活动。但是我想给代表打电话,而不是举办活动!似乎整个功能都是胡言乱语。非常感谢有些天才帮我正确转换这段代码......

1 个答案:

答案 0 :(得分:2)

在您的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