2011-10-28 139 views
0

如何將C#中的以下代碼轉換爲VB而不將「變量」暴露爲全局變量。將代表從C#轉換爲VB

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

回答

4

一個可能的解決

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語法糖用匿名代理做這樣的事情。

+0

這不起作用,因爲第一EndSub後,切斷了我的方法,而不是執行代碼的其餘部分: – checho

+0

它是不可訪問。一旦我添加結束函數VS自動將其更改爲結束小組(這會殺死我的方法) – checho

+0

我正在使用VS2008,這就是代碼無法工作的原因。我應該從一開始就添加這些信息。 如果你能想到VS2008的解決方案,我將非常感激。無論如何,我將此標記爲答案。 – checho

0

谷歌指出我在這個website它說他們是免費的。

+0

該轉換器無法正常工作。 – checho

+0

就像任何自動轉換工具一樣,它會有錯誤。你不能只依靠轉換器,你應該對兩種語言的關鍵字有不同的瞭解。我不知道VB,但我已經將VB代碼轉換爲C#,以便通過閱讀關鍵字文章來使用它。 –

+0

以下是我使用之間進行轉換兩種:VB和C#的比較(http://www.harding.edu/fmccown/vbnet_csharp_comparison.html) –