匿名方法 - C#到VB.NET

时间:2009-08-02 23:29:52

标签: c# vb.net event-handling anonymous-methods

我需要在终端服务器上实现应用程序的单个VB.NET实例。为此,我使用的是Flawless Code博客中的代码。它运行良好,除了代码是用C#编写并使用VB.NET不支持的匿名方法。我需要重写以下内容,以便将其用作VB.NET中的事件。

static Form1 form;

static void singleInstance_ArgumentsReceived(object sender, ArgumentsReceivedEventArgs e)
    {
        if (form == null)
            return;

        Action<String[]> updateForm = arguments =>
            {
                form.WindowState = FormWindowState.Normal;
                form.OpenFiles(arguments);
            };
        form.Invoke(updateForm, (Object)e.Args); //Execute our delegate on the forms thread!
    }
}

3 个答案:

答案 0 :(得分:6)

您可以使用此代码:

Private Shared form As Form1

Private Shared Sub singleInstance_ArgumentsReceived(ByVal sender As Object, ByVal e As ArgumentsReceivedEventArgs)
    If form Is Nothing Then Return
    form.Invoke(New Action(Of String())(AddressOf updateFormMethod), e.Args)
End Sub

Private Shared Sub updateFormMethod(ByVal arguments As String())
    form.WindowState = FormWindowState.Normal
    form.OpenFiles(arguments)
End Sub

答案 1 :(得分:4)

在VS 2010的VB.NET中,您可以执行以下操作:

Shared form As Form1
Shared Sub singleInstance_ArgumentsReceived(ByVal sender As Object, ByVal e As ArgumentsReceivedEventArgs)
    If form Is Nothing Then Return

    Dim updateForm As Action(Of String()) = Sub(arguments)
                                                form.WindowState = FormWindowState.Normal
                                                form.OpenFiles(arguments)
                                            End Sub

    form.Invoke(updateForm, e.args)

End Sub

答案 2 :(得分:3)

此:

public void Somemethod()
{
    Action<String[]> updateForm = arguments =>
        {
            form.WindowState = FormWindowState.Normal;
            form.OpenFiles(arguments);
        };
}

与:

相同
public void Somemethod()
{
    Action<String[]> updateForm = OnAction;
}

//named method
private void OnAction(string[] arguments)
{
    form.WindowState = FormWindowState.Normal;
    form.OpenFiles(arguments);
}

然后你可以轻松地进行VB.net转换,如下所示:

Public Sub SomeMethod()

    Dim updateForm As Action(Of String()) = New Action(Of String())(AddressOf Me.OnAction)
    Me.form.Invoke(updateForm, New Object() { e })

End Sub

Private Sub OnAction(ByVal arguments As String())
    form.WindowState = FormWindowState.Normal
    form.OpenFiles(arguments)
End Sub