简体   繁体   English

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

[英]How to use a common interface between SerialPort and NetworkStream in C#?

I have a C# method _TryReadChunk that reads bytes from a SerialPort connection: 我有一个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);
    ...
}

I need the same method again, but reading from a NetworkStream. 我需要再次使用相同的方法,但是从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. 但是,我不知何故需要在T必须实现Read方法的方法中添加约束。 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. 但是当阅读更多时,我得到的印象是SerialPort和NetworkStream必须明确地实现该接口,当然,他们没有。

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. SerialPort有一个名为BaseStream的属性,它是一个Stream。 NetworkStream also derives from stream, so you could do something like this: NetworkStream也派生自流,所以你可以这样做:

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. 然后传入SerialPort.BaseStream对象或NetworkStream对象,然后可以使用标准的Stream.Read方法以相同的方式读取数据。

You don't have to re implement which is already available. 您不必重新实施已经可用的功能。 You can use the SerialPort.BaseStream property and use it directly. 您可以使用SerialPort.BaseStream属性并直接使用它。

NetworkStream is already a Stream and SerialPort.BaseStream exposes a Stream . NetworkStream已经是StreamSerialPort.BaseStream公开了一个Stream You can take Stream as a parameter to your TryReadChunk method and read the stream directly. 您可以将Stream作为TryReadChunk方法的参数并直接读取流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM