问题描述
我正在调用一个写入流的 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.
这篇关于实现自定义流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!