C# 尝试读取数据时出现奇怪的问题
当我写作时:C# 尝试读取数据时出现奇怪的问题,c#,long-integer,binaryreader,C#,Long Integer,Binaryreader,当我写作时: var tagType = _reader.ReadByte(); while (tagType != 8) { var skip = ReadNext3Bytes() + 11; _reader.BaseStream.Position += skip; tagType = _reader.ReadByte(); } var tagType = _reader.ReadByte(); while (tagType != 8) { _reade
var tagType = _reader.ReadByte();
while (tagType != 8)
{
var skip = ReadNext3Bytes() + 11;
_reader.BaseStream.Position += skip;
tagType = _reader.ReadByte();
}
var tagType = _reader.ReadByte();
while (tagType != 8)
{
_reader.BaseStream.Position += ReadNext3Bytes() + 11;
tagType = _reader.ReadByte();
}
…它起作用了,但当我写:
var tagType = _reader.ReadByte();
while (tagType != 8)
{
var skip = ReadNext3Bytes() + 11;
_reader.BaseStream.Position += skip;
tagType = _reader.ReadByte();
}
var tagType = _reader.ReadByte();
while (tagType != 8)
{
_reader.BaseStream.Position += ReadNext3Bytes() + 11;
tagType = _reader.ReadByte();
}
…它不起作用,我不明白为什么-我得到了意想不到的结果。以下是ReadNext3Bytes
方法:
private long ReadNext3Bytes()
{
try
{
return Math.Abs((_reader.ReadByte() & 0xFF) * 256 * 256 + (_reader.ReadByte() & 0xFF)
* 256 + (_reader.ReadByte() & 0xFF));
}
catch
{
return 0;
}
}
为什么会这样,我该如何修复它
谢谢。这是因为在ReadByte调用期间位置发生了变化,您看到的情况与此类似:
int position = 1;
position += (position = 2) + 3;
Assert.AreEqual(6, position);
你说的“它不工作”是什么意思?正在引发异常?你得到了意想不到的结果?是的,我得到了意想不到的结果。你期望得到什么结果?你得到了什么样的结果?.NET在开始评估作业的右侧之前存储Position的值,最好的方法是最简单的方法:你写的第一个有效的表单。第二种方法,我不太喜欢的是从增量表达式中减少3:_reader.BaseStream.Position+=ReadNext3Bytes()+11-3;