是否可以使用VB 9.0将以下C#代码翻译成VB.NET?
delegate Stream StreamOpenerDelegate(String name);
void Exec1()
{
WorkMethod( x => File.OpenRead(x));
}
void Exec2()
{
StreamOpenerDelegate opener = x => return File.OpenRead(x) ;
WorkMethod(opener);
}
我可以这样做吗?:
Private Delegate Function StreamOpenerDelegate(ByVal name As String) As Stream
Private Sub WorkMethod(ByVal d As StreamOpenerDelegate)
''
End Sub
Private Sub Exec1()
Me.WorkMethod(Function (ByVal x As String)
Return File.OpenRead(x)
End Function)
End Sub
Private Sub Exec2()
Dim opener As StreamOpenerDelegate = Function (ByVal x As String)
Return File.OpenRead(x)
End Function
Me.WorkMethod(opener)
End Sub
我正在尝试编写一些文档,但我不知道VB语法。我经常使用Reflector来翻译它,但我不确定它是否适用于这种情况。我也不清楚我在哪里需要续行字符。
ANSWER
在VB9中,不可能有多行lambdas(或Sub lambdas,我没有问过)。在VB9中,所有lambdas都返回一个值,并且必须是单个表达式。这改变了VB10。 VB10将允许上面的语法,但VB9不会。在VB9中,如果逻辑涉及多个代码行,则它不能是lambda;你必须将它放入一个命名函数并明确引用它。像这样:
Private Delegate Function StreamOpenerDelegate(ByVal name As String) As Stream
Private Sub WorkMethod(ByVal d As StreamOpenerDelegate)
''
End Sub
Function MyStreamOpener(ByVal entryName As String) As Stream
'' possibly multiple lines here
Return File.OpenRead(entryName)
End Function
Private Sub Exec1()
Me.WorkMethod(AddressOf MyStreamOpener)
End Sub
答案 0 :(得分:2)
这应该有效:
Private Sub Exec1()
Me.WorkMethod(Function (x) File.OpenRead(x))
End Sub
Private Sub Exec2()
Dim opener As StreamOpenerDelegate = Function (x) File.OpenRead(x)
Me.WorkMethod(opener)
End Sub
您需要行继续符将单行语句拆分为多行,如下所示:
Private Sub Exec1()
Me.WorkMethod(Function (x) _
File.OpenRead(x))
End Sub
Private Sub Exec2()
Dim opener As StreamOpenerDelegate = Function (x) _
File.OpenRead(x)
Me.WorkMethod(opener)
End Sub
在任何情况下,在VS2010中,在某些字符之后存在隐式行继续。所以我不会太担心它。