我正在尝试编写一个C#匿名函数的VB.NET替代。
我希望调用Threading.SynchronizationContext.Current.Send,它希望将Threading.SendOrPostCallback类型的委托传递给它。背景是here,但因为我希望将字符串传递给MessageBox.Show并捕获DialogResult,我需要在其中定义另一个委托。我正在努力使用VB.NET语法,包括传统的委托样式和lambda函数。
我的传统语法如下,但我觉得它应该比这简单得多:
Private Sub CollectMesssageBoxResultFromUserAsDelegate(ByVal messageToShow As String, ByRef wasCanceled As Boolean)
wasCanceled = False
If Windows.Forms.MessageBox.Show(String.Format("{0}{1}Please press [OK] to ignore this error and continue, or [Cancel] to stop here.", messageToShow), "Continue", Windows.Forms.MessageBoxButtons.OKCancel, Windows.Forms.MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Cancel Then
wasCanceled = True
End If
End Sub
Private Delegate Sub ShowMessageBox(ByVal messageToShow As String, ByRef canceled As Boolean)
Private Sub AskUserWhetherToCancel(ByVal message As String, ByVal args As CancelEventArgs)
If args Is Nothing Then args = New System.ComponentModel.CancelEventArgs With {.Cancel = False}
Dim wasCancelClicked As Boolean
Dim firstDelegate As New ShowMessageBox(AddressOf CollectMesssageBoxResultFromUserAsDelegate)
'…. Now what??
'I can’t declare SendOrPostCallback as below:
'Dim myDelegate As New Threading.SendOrPostCallback(AddressOf firstDelegate)
End Sub
答案 0 :(得分:4)
我认为处理此问题的最简单方法是创建一个包装消息框显示的新对象。然后可以使用此对象检索结果。
例如:
Public Class Helper
Public WasCanceled as Boolean
Public Message As String
Public Done as New ManualResetEvent(false)
Public Sub New(message as String)
Me.Message = message
End Sub
Public Sub ShowMessageBox(unused as Object)
If MessageBox.Show(Message) = DialogResult.Cancel Then
WasCanceled = True
Done.Set()
End Sub
End Class
Public Sub AskUserWhetherToCancel(context as SynchronizationContext, message As String)
Dim helper As New Helper(message)
context.Post(AddressOf helper.ShowMessageBox, Nothing)
' Wait for it to finish
helper.WaitOne()
if helper.WasCanceled Then
...
Else
...
End IF
End Sub
答案 1 :(得分:1)
试试这个:
Dim myDelegate As New Threading.SendOrPostCallback(Function(c) firstDelegate)
不确定它是否能完全按照你的意愿工作,但它会编译。
也许这就是你要找的东西:Passing parameters to delegates in VB.NET