委托功能不返回值

时间:2014-05-06 11:47:07

标签: vb.net function delegates return return-value

我可能会遗漏一些明显的东西,但我无法通过委托返回值。

Private Delegate Sub ChangeTextDelegate(tb As TextBox)
Private Sub ChangeText(tb As TextBox)
    If tb.InvokeRequired Then
        tb.Invoke(New ChangeTextDelegate(AddressOf ChangeText), tb)
    Else
        tb.Text = "NEW TEXT"
    End If
End Function

Sub Delegate运作良好。

Private Delegate Function TextLengthDelegate(tb As TextBox) As Integer
Private Function TextLength(tb As TextBox) As Integer
    If tb.InvokeRequired Then
        tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)
    Else
        Return tb.TextLength
    End If
End Function

但是这个功能代表似乎在i == 0 dim i = TextLength(myTextBox)之后无效,即使tb.TextLength == 68

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

如果需要Invoke ,则不返回该值。

请改为尝试:

Private Delegate Function TextLengthDelegate(tb As TextBox) As Integer
Private Function TextLength(tb As TextBox) As Integer
    If tb.InvokeRequired Then
        Return CInt(tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb))
    Else
        Return tb.TextLength
    End If
End Function

但是,您可能会发现此代码更容易,因为您不必定义单独的委托:

Private Function TextLength(tb As TextBox) As Integer
    If tb.InvokeRequired Then
        Return CType(tb.Invoke(New Action(Of TextBox)(AddressOf TextLength), tb), Integer)
    Else
        Return tb.TextLength
    End If
End Function

答案 1 :(得分:1)

VS是否警告您有关您的代码,因为它在调用委托时没有返回值?

tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)

您必须返回Invoke返回的值,自Invoke returns an Object起,您需要转换值:

Dim result = tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)
Return DirectCast(result, Integer)