您好我一直在尝试将用C#编写的示例项目转换为VB.NET,并且我已成功纠正了大多数错误,请注意以下两项。任何有关转换的提示都将受到赞赏:
原始C#代码如下:
public event EventHandler<ExplorerErrorEventArgs> ExplorerError;
private void InvokeExplorerError(ExplorerErrorEventArgs e)
{
EventHandler<ExplorerErrorEventArgs> handler = ExplorerError;
if (handler != null) handler(this, e);
}
public ExplorerTreeView()
{
Loaded += (s, e) => InitExplorer();
SelectedItemChanged += OnSelectedItemChanged;
AddHandler(TreeViewItem.ExpandedEvent, new RoutedEventHandler(OnItemExpanded));
AddHandler(TreeViewItem.CollapsedEvent, new RoutedEventHandler(OnItemCollapsed));
}
转换后的VB.NET代码在这里:
Public Event ExplorerError As EventHandler(Of ExplorerErrorEventArgs)
Private Sub InvokeExplorerError(e As ExplorerErrorEventArgs)
Dim handler As EventHandler(Of ExplorerErrorEventArgs) = ExplorerError
RaiseEvent handler(Me, e)
End Sub
Public Sub New()
Loaded += Function(s, e) InitExplorer()
SelectedItemChanged += OnSelectedItemChanged
[AddHandler](TreeViewItem.ExpandedEvent, New RoutedEventHandler(OnItemExpanded))
[AddHandler](TreeViewItem.CollapsedEvent, New RoutedEventHandler(OnItemCollapsed))
End Sub
问题领域是:
Dim handler As EventHandler(Of ExplorerErrorEventArgs) = ExplorerError
使用错误强调ExplorerError:
Public Event ExplorerError(sender As Object,e As ExplorerErrorEventArgs)'是一个事件,无法直接调用。使用'RaiseEvent'语句来引发事件。
其次:
Loaded += Function(s, e) InitExplorer()
产生错误:
公共事件已加载(sender As Object,e As System.Windows.RoutedEventArgs)'是一个事件,无法直接调用。使用'RaiseEvent'语句来引发事件。
在s,e和InitExplorer下也有错误曲线,但我怀疑整行都存在语法问题。 InitExplorer()是一个没有参数的Sub。
我已经阅读了很多文章来尝试并获得想法,但我还没有提出任何建议。任何提示将非常感谢!提前谢谢。
答案 0 :(得分:3)
在VB.NET中,您可以对事件做的唯一事情是raise them或add / remove处理程序。它们不能在委托对象中引用:
Dim handler As EventHandler(Of ExplorerErrorEventArgs) = ExplorerError
你可能想要
Dim args = New ExplorerErrorEventArgs()
'fill args with any extra data
RaiseEvent ExplorerError(args)
C#允许您直接引用事件,作为引发事件的快捷方式:
ExplorerError(new ExplorerErrorEventArgs());
同样,这个用于添加处理程序的C#快捷方式:
Loaded += (s,e) InitExplorer();
VB.NET不支持。您必须将此用于第二期:
AddHandler Loaded, Sub(s,e) InitExplorer()
答案 1 :(得分:3)
事件部分可以简单地重写为:
RaiseEvent ExplorerError(Me, e)
第二个,Loaded
的处理程序可以简单地写成:
AddHandler Loaded,
Sub(s as Object, e as EventArgs)
InitExplorer()
EndSub
答案 2 :(得分:2)
通过使用隐藏的“事件”,可以在VB中轻松处理第一个问题。 VB中的字段(存在于这种情况下)。以下编译在VB中很好:
Public Event ExplorerError As EventHandler(Of ExplorerErrorEventArgs)
Private Sub InvokeExplorerError(ByVal e As ExplorerErrorEventArgs)
'note the "Event" added to the end of "ExplorerError":
Dim handler As EventHandler(Of ExplorerErrorEventArgs) = ExplorerErrorEvent
If handler IsNot Nothing Then
handler(Me, e)
End If
End Sub
VB事件真的是一个包装原始&#39;原始&#39;我们在C#中举办的活动 - 活动&#39; field只是VB事件包装的原始事件。