What is the VB equivalent of this C# syntax, deali

2019-07-13 19:10发布

Is it possible to translate the following C# code into VB.NET, using VB 9.0?

delegate Stream StreamOpenerDelegate(String name);

void Exec1()
{
    WorkMethod( x => File.OpenRead(x));
}

void Exec2()
{
    StreamOpenerDelegate opener = x => return File.OpenRead(x) ;
    WorkMethod(opener);
}

Can I do something like this?:

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

I'm trying to write some documentation, but I don't know VB syntax. Often I use Reflector to translate it, but I'm not sure it's working in this case. I'm also not clear on where I would need line continuation characters.


ANSWER
In VB9, it's not possible to have multi-line lambdas (or Sub lambdas, which I did not ask about). In VB9, all lambdas return a value, and must be a single expression. This changes in VB10. VB10 will allow the above syntax, but VB9 will not. In VB9, if the logic involves multiple code lines, it must not be a lambda; you must put it into a named Function and reference it explicitly. Like this:

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

site: Mike McIntyre's blog

1条回答
孤傲高冷的网名
2楼-- · 2019-07-13 19:59

This should work:

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

You need the line continuation character to split a single line statement into multiple lines, like so:

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

In any case, in VS2010 there is implicit line continuation after certain characters. So I wouldn't worry about it too much.

查看更多
登录 后发表回答