Getting derived object from the base object
I extended the System.Net.Sockets.TcpClient class and I cannot figure out how to get an instance of my derived class when given an instance of the base TcpClient class.
For example, the TcpListner.AcceptTcpClient() method returns a TcpClient object. I would like to take that and get an instance of my derived class.
I tried to just cast it, but I get an invalid cast error - which I expected since the base object wasn't boxed from the derived object.
I tried to just assign the base object in the constructor of the derived class:
new MyTcpClient(TcpClient client) {
base = client;
}
but it wouldn't compile - "Use of keyword base is not valid in this context".
Can something like this even be done?
shimtannyPosted Oct 7, 2004, 12:35 PM
shimtannyPosted Oct 7, 2004, 12:28 PM
jsheplerPosted Oct 7, 2004, 9:53 AM
public class MyTcpClient : TcpClient { public int ResourceIndex = -1; private NetworkStream ns; public delegate void TcpObjectHandler (TCPClient client, Infob iob); public event TcpObjectHandler ObjectArrived; public MyTcpClient() : base() {} public MyTcpClient(IPEndPoint localEP) : base(localEP) {} public MyTcpClient(AddressFamily family) : base(family) {} public MyTcpClient(string hostname, int port) : base(hostname, port) {} .... }Now, I set up a TcpListener object that has a method AcceptTcpClient() which returns a TcpClient object. I need to take that object and get an instance of MyTcpClient. Doing this:TcpListener listener = new TcpListener(IPAddress.Any, port); listener.Start(); while(true) { Thread.Sleep(1000); if(!listener.Pending()) continue; MyTcpClient newClient = (MyTcpClient)listener.AcceptTcpClient(); ... }fails during runtime - invalid cast exception. I expected this because the TcpClient object that AcceptTcpClient() returned wasn't boxed from MyTcpClient originally, so the cast fails. My next attempt was to add another constructor to MyTcpClient that took an instance of TcpClient and tried to assign it to base, like so:public MyTcpClient (TcpClient client) { base = client; }which failed to compile - cannot use the base keyword in that context. So, my problem/question is - how do I get an instance of a derived object from an instance of the base object?shimtannyPosted Oct 7, 2004, 5:19 AM
jsheplerPosted Oct 6, 2004, 2:44 PM
jsheplerPosted Oct 5, 2004, 2:43 PM
shimtannyPosted Oct 5, 2004, 1:24 PM