0

我在 VB.NET 中有一个应用程序 当我在 Visual Studio 2010 中运行该应用程序并将鼠标悬停在一个IAsyncResult时,我看到了受保护的属性Result。我想读取应用程序中属性的值。我怎样才能做到这一点?

Imports System.Net
Imports System.Net.Sockets
...

Friend Function StartSendGo() As String

    'Declarations
    Dim strSendMachineName As String = "DEV001"
    Dim intSendPort As Integer = 50035
    Dim socketclient As New System.Net.Sockets.TcpClient()


    Dim rslt As IAsyncResult = tcpClient.BeginConnect(strSendMachineName, intSendPort, New AsyncCallback(AddressOf ConnectCallback), socketclient)
    Dim blnSuccess = rslt.AsyncWaitHandle.WaitOne(intTimeOutConnect, True)
    'HERE is where I need rslt.Result.Message

End Function

Public Function ConnectCallback()
    'Placeholder
End Function

当我将鼠标悬停在 rslt 上时,VS 显示它是 System.Net.Sockets.Socket+MultipleAddressConnectAsyncResult我以前从未在类型中看到过加号 (+) 的类型,并且我无法声明该类型的变量。如果我展开属性,就会有一个受保护的属性Result,它的属性Message值为"No connection could be made because the target machine actively refused it 192.0.0.10:50035"。我需要访问该消息。我也想访问addresses,但这并不重要。

4

1 回答 1

0

我找到了一个解决方案——使用反射来读取私有属性的值。

'Imports
Imports System.Reflection


'Call functions that write to rslt
rslt = tcpClient.BeginConnect(strSendMachineName, intSendPort, New AsyncCallback(AddressOf ConnectCallback), socketclient)
blnSuccess = rslt.AsyncWaitHandle.WaitOne(intTimeOutConnect, True)

'Use Reflection
'Get Type
Dim myType As Type = rslt.GetType()
'Get properties
Dim myPropertyInfo As PropertyInfo() = myType.GetProperties((BindingFlags.NonPublic Or BindingFlags.Instance))
'The order of the properties is not guaranteed. Find by name.
For Each pi As PropertyInfo In myPropertyInfo
    If pi.Name = "Result" Then
        'TODO Add check for nothing.
        'Assign to Exception-type variable.
        exException = pi.GetValue(rslt, Nothing)
    End If
Next
于 2013-10-01T18:28:49.430 回答