如何在C#中使用SerialPort和NetworkStream之间的公共接口?

如何在C#中使用SerialPort和NetworkStream之间的公共接口?,c#,generics,interface,C#,Generics,Interface,我有一个C#方法"TryReadChunk,它从SerialPort连接读取字节: 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); ... } 我需要同样的方法,但

我有一个C#方法"TryReadChunk,它从SerialPort连接读取字节:

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);
    ...
}
我需要同样的方法,但是从网络流读取。我认为一个优雅的方法是使用一个通用的方法,比如

private bool _TryReadChunk<T> (T connection, int n_exp, out byte[] received)
{
    ...
}
并要求

private bool _TryReadChunk<T> (T connection, int n_exp, out byte[] received) where T : _CanRead
{
    ...
}
private bool\u TryReadChunk(T connection,int n\u exp,out byte[]received),其中T:\u可以读取
{
...
}
但是在阅读更多内容时,我得到的印象是SerialPort和NetworkStream必须显式地实现该接口,当然,它们没有


我不熟悉泛型,感觉有点卡住了。有什么方法可以实现我想要的,或者我应该咬紧牙关,实现我的方法两次吗?

这可能不是泛型的好应用程序,但它是用于使用基类的。SerialPort有一个名为BaseStream的属性,它是一个流。NetworkStream还派生自stream,因此您可以执行以下操作:

private bool _TryReadChunk(Stream connection, int n_exp, out byte[] received)
{
    ...
}

然后传入对象或NetworkStream对象,然后可以使用标准Stream.Read方法以相同的方式读取数据。

您不必重新实现已经可用的方法。您可以使用
SerialPort.BaseStream
属性并直接使用它


NetworkStream
已经是
SerialPort。BaseStream
公开
。您可以将
Stream
作为
tryreadcunk
方法的参数,直接读取流。

谢谢。我已经检查了公共基类,但没有检查属性之间的公共基类。
private bool _TryReadChunk(Stream connection, int n_exp, out byte[] received)
{
    ...
}