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

Get async result from TCPClient.BeginConnect's callback method

这是我的代码:

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 没有几个有用的方法。我无法从中获取执行结果的详细信息。当我调试这段代码时,我发现我想要的东西如下: 如何访问非 Public 成员?

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

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

基本上我们反思我们需要的类型(type of IAsyncResult via ar)然后指定我们感兴趣的field/property("ErrorCode"),然后获取它的特定实例的值(ar).

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