I have a C# method _TryReadChunk that reads bytes from a 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 the same method again, but reading from a NetworkStream. I thought that an elegant way to do this would be to use a generic method like
private bool _TryReadChunk<T> (T connection, int n_exp, out byte[] received)
{
...
}
However, I somehow need to add a constraint to the method that T has to implement a Read method. First I thought to define an 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) where T : _CanRead
{
...
}
but when reading more I got the impression that SerialPort and NetworkStream would have to implement that interface explicitly, which, of course, they don't.
I am new to generics and feel a bit stuck. Is there a way to do what I want or should I just bite the bullet and implement my method twice?
This probably isn't a good application for generics, but it is for using base classes. SerialPort has a property called BaseStream, which is a Stream. NetworkStream also derives from stream, so you could do something like this:
private bool _TryReadChunk(Stream connection, int n_exp, out byte[] received)
{
...
}
Then pass in the SerialPort.BaseStream object or the NetworkStream object, you can then use the standard Stream.Read methods to read the data out the same way.
You don't have to re implement which is already available. You can use the SerialPort.BaseStream
property and use it directly.
NetworkStream
is already a Stream
and SerialPort.BaseStream
exposes a Stream
. You can take Stream
as a parameter to your TryReadChunk
method and read the stream directly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.