我正在搜索BinaryReader.Skip函数,而我在msdn上遇到了这个功能请求.他说你可以使用它来提供你自己的BinaryReader.Skip()函数.
只看这段代码,我想知道为什么他选择这种方式跳过一定数量的字节:
for (int i = 0, i < count; i++) {
reader.ReadByte();
}
Run Code Online (Sandbox Code Playgroud)
它和之间有区别吗:
reader.ReadBytes(count);
Run Code Online (Sandbox Code Playgroud)
即使它只是一个小的优化,我也不愿意.因为现在它对我来说没有意义,为什么你会使用for循环.
public void Skip(this BinaryReader reader, int count) {
if (reader.BaseStream.CanSeek) {
reader.BaseStream.Seek(count, SeekOffset.Current);
}
else {
for (int i = 0, i < count; i++) {
reader.ReadByte();
}
}
}
Run Code Online (Sandbox Code Playgroud)
不,没有区别。 编辑:假设流有足够的再见
该ReadByte方法只是转发到底层 Stream 的ReadByte方法。
该ReadBytes方法调用底层流,Read直到读取所需的字节数。
它的定义如下:
public virtual byte[] ReadBytes(int count) {
if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
Contract.EndContractBlock();
if (m_stream==null) __Error.FileNotOpen();
byte[] result = new byte[count];
int numRead = 0;
do {
int n = m_stream.Read(result, numRead, count);
if (n == 0)
break;
numRead += n;
count -= n;
} while (count > 0);
if (numRead != result.Length) {
// Trim array. This should happen on EOF & possibly net streams.
byte[] copy = new byte[numRead];
Buffer.InternalBlockCopy(result, 0, copy, 0, numRead);
result = copy;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
对于大多数流,ReadBytes可能会更快。
| 归档时间: |
|
| 查看次数: |
3283 次 |
| 最近记录: |