【问题标题】:Convert delegate from C# to VB将委托从 C# 转换为 VB
【发布时间】:2011-10-28 14:04:52
【问题描述】:

如何在不将“变量”暴露为全局变量的情况下将以下代码从 C# 转换为 VB。

private void SomeMethod(SomeType variable)
{
    this.SomeEvent+= delegate
    {
        if (variable == 1)
        {
           this.DoSomething();
        }
    }
    //here I have some other code
}

【问题讨论】:

    标签: c# vb.net delegates


    【解决方案1】:

    一种可能的解决方案

    Private Sub SomeMethod(ByVal variable As Integer)
        AddHandler Me.SomeEvent,
            Sub()
                If (variable = 1) Then
                    Me.DoSomething()
                End If
            End Sub
        Console.WriteLine("ciao")
    End Sub
    

    我刚刚尝试过,它就像一个魅力,所以我不知道你为什么说它没有:(Visual Studio 2010。

    你也可以这样做

    Private Sub SomeMethod(ByVal variable As Integer)
        Me.SomeEvent = DirectCast(Delegate.Combine(Me.SomeEvent, Sub()
            If (variable = 1) Then
                Me.DoSomething
            End If
        End Sub), MyDelegate)
        ...mycode
    End Sub
    

    Delegate.Combine 和 AddHandler 的效果完全一样。

    我没有Visual Studio 2008,所以我不知道如何在VS2008中编写,尝试第二个解决方案,第一个似乎只适用于2010。

    如果这不起作用你可以试试这个,更多的代码要写:

    Public Delegate Sub MyDelegate()
    
    Public Class Class1
    
        Public Event SomeEvent As MyDelegate
    
        Private Class MyDelegateClass
    
            Public Owner As Class1
            Public Variable As Integer
    
            Public Sub Method()
                If (Variable = 1) Then
                    Owner.DoSomething()
                End If
            End Sub
    
        End Class
    
        Private Sub SomeMethod(ByVal variable As Integer)
    
            Dim dc As New MyDelegateClass
            dc.Owner = Me
            dc.Variable = variable
    
            AddHandler Me.SomeEvent, AddressOf dc.Method
            Console.WriteLine("ciao")
        End Sub
    
        Public Sub DoSomething()
            Console.WriteLine("hello")
        End Sub
    
    End Class
    

    Visual Studio 语法糖对匿名委托执行类似的操作。

    【讨论】:

    • 这不起作用,因为在第一个 EndSub 之后它切断了我的方法并且其余代码没有执行:
    • 无法访问。一旦我添加了 End Function VS 会自动将其更改为 End Sub (这会杀死我的方法)
    • 我正在使用 VS2008,这就是代码无法正常工作的原因。我应该从一开始就添加这些信息。如果您能想到 VS2008 的解决方案,我将不胜感激。无论如何,我将此标记为答案。
    【解决方案2】:

    Google 向我指出了这个 website,上面说他们是免费的。

    【讨论】:

    • 像任何自动转换工具一样,它会出现错误。您不能只依赖转换器,您应该对两种语言之间的关键字有何不同有所了解。我不了解 VB,但我已经将 VB 代码转换为 C#,仅用于阅读有关关键字的文章。
    • 这是我用来在两者之间转换的:VB and C# Comparison
    • 我经常将 C# 转换为 VB,但我仍然无法使用这个委托。
    • @checho 好吧,Ramhound 给了你一个链接,让你了解 VB 中的代表,Salvatore 为你提供了一个 VB 翻译。
    • 是的,他们都没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多