从TCPClient.BeginConnect的回调方法获取异步结果

时间:2016-01-28 02:20:32

标签: c# tcpclient

这是我的代码:

TcpClient _tcpClient = new TcpClient(AddressFamily.InterNetwork);

public void BeginConnect(string address, ushort port, OnConnectCallback cb) {
    IAsyncResult ar = _tcpClient.BeginConnect(address, port, ConnectCallback, cb);
}

private void ConnectCallback(IAsyncResult ar) {
    //The ar is acturally an instance of MultipleAddressConnectAsyncResult
    //it contains the execution result I want. 
    //However, MultipleAddressConnectAsyncResult class is not public.
    _tcpClient.EndConnect(ar);
}

如您所知,IAsyncResult几乎没有什么有用的方法。我无法从中获得执行结果的详细信息。当我调试这段代码时,我发现了我想要的东西如下: enter image description here 我如何访问非公开成员?

1 个答案:

答案 0 :(得分:0)

您可以在C#中使用反射来访问非公共方法。 请尝试以下代码段:

var errorCode = ar.GetType().GetProperty("ErrorCode", 
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ar);

基本上我们反思我们需要的类型(通过ar的IAsyncResult类型),然后指定我们感兴趣的字段/属性(" ErrorCode"),然后获取特定实例的值( AR)。

与GetProperty类似,有各种辅助方法可以获取字段,成员等的值,这些方法采用各种过滤器来获取所需的特定值。