【问题标题】:AcceptTcpClient() and class based on TcpClientAcceptTcpClient() 和基于 TcpClient 的类
【发布时间】:2011-11-24 03:18:54
【问题描述】:

我需要一个包含 TcpClient 所具有的所有内容 + 几个额外字段的类,所以我创建了一个基于 TcpClient 的类:

public class MyClient: TcpClient
{
    public string winUser;
    public bool needHelp;
    public bool needSignOff;

    public MyClient() : base() {
        this.needHelp = false;
        this.needSignOff = false;
        this.winUser = "empty";
    }
}

现在我需要将所有传入连接创建为此类的对象:

MyClient clientConnection = (MyClient)this.helpServer.AcceptTcpClient();

问题是 AcceptTcpClient() 生成一个 TcpClient 类对象,当我尝试连接到服务器时,我不断收到此异常:

listenServer():无法将“System.Net.Sockets.TcpClient”类型的对象转换为“Server.MyClient”类型。

如何将 AcceptTcpClient() 提供给我的 TcpClient 对象转换为 MyClient 对象?

【问题讨论】:

  • 这根本不可能。

标签: c# class inheritance tcpclient


【解决方案1】:

不可能将类型 (TcpClient) 向下转换为更派生的类型 (MyClient)。您必须更新 AcceptTcpClient 以返回 MyClient 对象。

【讨论】:

  • 如果你愿意,你能把它写成扩展AcceptTcpMyClient 等等吗?如果是的话,有没有关于如何获取源代码的详细信息?
猜你喜欢
  • 2013-07-05
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 2016-08-17
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多