generics - How to use a common interface between SerialPort and NetworkStream in C#? -
i have c# method _tryreadchunk reads bytes serialport connection:
private bool _tryreadchunk(serialport connection, int n_exp, out byte[] received) { ... received = new byte[n_exp]; int bytes_read = connection.read(received, length, n_exp); ... } i need same method again, reading networkstream. thought elegant way use generic method like
private bool _tryreadchunk<t> (t connection, int n_exp, out byte[] received) { ... } however, somehow need add constraint method t has implement read method. first thought define interface like
interface _canread { int read(byte[] buffer, int offset, int count); } and require
private bool _tryreadchunk<t> (t connection, int n_exp, out byte[] received) t : _canread { ... } but when reading more got impression serialport , networkstream have implement interface explicitly, which, of course, don't.
i new generics , feel bit stuck. there way want or should bite bullet , implement method twice?
this isn't application generics, using base classes. serialport has property called basestream, stream. networkstream derives stream, this:
private bool _tryreadchunk(stream connection, int n_exp, out byte[] received) { ... } then pass in serialport.basestream object or networkstream object, can use standard stream.read methods read data out same way.
Comments
Post a Comment