是否可以使用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进行翻译,但是我不确定在这种情况下它是否可以正常工作。我也不清楚在哪里需要换行符。



回答
在VB9中,不可能有多行lambda(或Sub lambda,我没有问过)。在VB9中,所有lambda都返回一个值,并且必须是单个表达式。这在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


网站:Mike McIntyre's blog

最佳答案

这应该工作:

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中,某些字符后都有隐式的行连续。因此,我不必担心太多。

关于c# - 处理委托(delegate)的这种C#语法的VB等价方式是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1771184/

10-10 15:18