Implement custom stream(实现自定义流)
问题描述
我正在调用一个写入流的 dll.dll中方法的签名如下:
I am calling a dll that writes to a stream. The signature of the method in the dll looks like:
public bool SomeMethod(Stream stream);
该方法基本上会将二进制数据写入该流.因此,如果我将该方法调用为:
and that method will basically write binary data to that stream. So if I will call that method as:
var file = System.IO.File.Create("SomeFile.txt");
/* call dll method */ SomeMethod(file);
然后我将基本上将输出写入该文件.在这个问题中,我将输出写入 networkStream.
then I will be basically writing the output to that file. In this question I am writing the output to a networkStream.
无论如何,回到问题.我想创建自己的流的原因是因为我想知道某些事件何时发生.例如,如果我在哪里创建自己的流类:
Anyways so back to the question. The reason why I will like to create my own stream is because I will like to know when some events take place. For example if I where to create my own stream class as:
class MyStream : Stream
{
private long Position;
public override int Read(byte[] buffer, int offset, int count)
{
// implementation goes here
/* HERE I COULD CALL A CUSTOM EVENT */
}
public override long Seek(long offset, SeekOrigin origin)
{
// SAME THING I WILL LIKE TO PERFORM AN ACTION IF THIS METHOD IS CALLED!
}
// etc implement rest of abstract methods....
我正在将该流的输出写入网络,因此如果发生某些事件,我可能想放慢速度.如果我在哪里可以控制 dll,那么我就不会尝试实现这一点.
I am writing the output of that stream to the network so I might want to slow down if some event occurs. If I where to have control of the dll then I would not be trying to implement this.
如果有人可以向我展示如何实现抽象流类的抽象方法的非常基本的示例,我将不胜感激.
I will appreciate if someone could show me a very basic example of how to implement the abstract methods of the abstract Stream Class.
推荐答案
最简单的自定义流包装"其他一些流(类似于压缩流)的流.每个方法都会简单地将其实现重定向到内部流.
The easiest custom stream a stream that "wraps" some other stream (similar to compression streams). Each method would simply redirect its implementation to internal stream.
class MyStream : Stream
{
Stream inner;
public MyStream(Stream inner)
{
this.inner = inner;
}
public override int Read(byte[] buffer, int offset, int count)
{
var result = inner.Read(buffer, offset, count);
/* HERE I COULD CALL A CUSTOM EVENT */
return result;
}
///
}
使用示例:functionThatTakesStream(new MyStream(new MemoryStream());
.
实际代码需要在触发事件之前/之后处理内部流操作中的异常,并正确处理 IDisposable.
Real code will need to handle exceptions in operations on inners stream before/after fireing events and deal with IDisposable correctly.
这篇关于实现自定义流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实现自定义流
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01