如何解决在.net中将父类转换为子类的困难?

如何解决在.net中将父类转换为子类的困难?,.net,casting,parent-child,.net,Casting,Parent Child,我有这个: public class ClientSession : TcpClient { public int SessionGUID = 0; } 在服务器线程中的某个地方: ClientSession client = (ClientSession)tcpListener.AcceptTcpClient(); //cast failure 好的,我知道要这样强制转换,右侧对象必须是ClientSession的实例,它可能存储在指向基类的指针中 但是在这种情况下,如何构造Cli

我有这个:

public class ClientSession : TcpClient
{
    public int SessionGUID = 0;
}
在服务器线程中的某个地方:

ClientSession client = (ClientSession)tcpListener.AcceptTcpClient(); //cast failure
好的,我知道要这样强制转换,右侧对象必须是ClientSession的实例,它可能存储在指向基类的指针中 但是在这种情况下,如何构造ClientSession

我不想让ClientSession变成这样:

public class ClientSession
{
    public int SessionGUID = 0;
    public TcpClient client;
}
TcpListener.AcceptTcpClient将返回一个TcpClient对象,而不返回其他对象。无法在运行时更改对象的类型,因此不可能进行保留对象标识和数据的直接转换

我认为与上一个代码片段类似的组合是最好的方法。您可以通过实现自定义转换运算符来使用强制转换语法启用转换,但我更建议您在此处使用接受TcpClient的构造函数:

所以你可以这样做:

ClientSession client = new ClientSession(tcpListener.AcceptTcpClient());
所有ClientSession均为TcpClient类型,但并非所有TcpClient均为ClientSession类型。tcpListener.AcceptTcpClient返回TcpClient的对象,它不能用作ClientSession。或者,您可以如下调整您的类:

class ClientSession
{
    public ClientSession(TcpClient client) 
    {
        this.client = client;
    }
    public TcpClient client {get; set;}
    // your stuff here...
}

这不是我想要的,我知道我不能这样投,我写在主要问题,我只是想找到一种方式,以某种方式投下它。。。既然你的答案是第一,我就接受it@Kosmos您不能,因为无法在运行时更改对象的类型。一旦有了TcpClient,它就会保持不变,因此我看到的唯一解决方案是使用TcpClient as字段构建ClientSession。
class ClientSession
{
    public ClientSession(TcpClient client) 
    {
        this.client = client;
    }
    public TcpClient client {get; set;}
    // your stuff here...
}