我正在尝试装饰 Stream
类 CaesarStream
类,基本上将凯撒密码应用于 Read
和Write
运营。我已经设法覆盖 Write
方法很容易,但是 Read
让我头疼。据我了解,我需要调用底层 FileStream
的Read
方法并以某种方式修改它,但是如何让它读取值,同时向每个字节添加一个数字,类似于我在 Write()
中所做的方法?这对我来说更难,因为Read
的返回值只是读取的字节数,而不是实际读取的项。
public class CaesarStream : Stream
{
private int _offset;
private FileStream _stream;
public CaesarStream(FileStream stream, int offset)
{
_offset = offset;
_stream = stream;
}
public override int Read(byte[] array, int offset, int count)
{
//I imagine i need to call
//_stream.Read(array, offset, count);
//and modify the array, but how do i make my stream return it afterwards?
//I have no access to the underlying private FileStream fields so I'm clueless
}
public override void Write(byte[] buffer, int offset, int count)
{
byte[] changedBytes = new byte[buffer.Length];
int index = 0;
foreach (byte b in buffer)
{
changedBytes[index] = (byte) (b + (byte) _offset);
index++;
}
_stream.Write(changedBytes, offset, count);
}
}
PS 我知道我还应该检查读/写的字节数并继续读/写直到完成,但我还没有做到这一点。我想先完成阅读部分。
最佳答案
按照尤金的建议,我设法让它按预期工作,下面是代码,以防有人想看它:
public class CaesarStream : Stream
{
private int _offset;
private FileStream _stream;
public CaesarStream(FileStream stream, int offset)
{
_offset = offset;
_stream = stream;
}
public override int Read(byte[] array, int offset, int count)
{
int retValue = _stream.Read(array, offset, count);
for (int a = 0; a < array.Length; a++)
{
array[a] = (byte) (array[a] - (byte) _offset);
}
return retValue;
}
public override void Write(byte[] buffer, int offset, int count)
{
byte[] changedBytes = new byte[buffer.Length];
int index = 0;
foreach (byte b in buffer)
{
changedBytes[index] = (byte) (b + (byte) _offset);
index++;
}
_stream.Write(changedBytes, offset, count);
}
}
关于c# - 使用自定义 Read() 和 Write() 功能装饰 FileStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36669138/