我正在写一个固定长度的文件阅读器。我已经建立了一个Attribute
类,用于定义文件中每个字段的索引和长度:
[AttributeUsage(AttributeTargets.Field)]
public class FixedAttribute : Attribute
{
public int Index { get; private set; }
public int Length { get; private set; }
public FixedAttribute(int index, int length)
{
this.Index = index;
this.Length = length;
}
}
还有Reader
类:
public class FixedReader
{
private readonly Stream stream;
private byte[] buffer;
public FixedReader(Stream stream)
{
this.stream = stream;
this.buffer = new byte[4];
}
public void Read<T>(T data)
{
var fields = typeof(T).GetFields();
foreach (var field in fields)
{
var attrib = field.GetCustomAttribute(typeof(FixedAttribute)) as FixedAttribute;
if (attrib == null)
continue;
stream.Seek(attrib.Index, SeekOrigin.Begin);
if (buffer.Length < attrib.Length)
{
buffer = new byte[attrib.Length];
}
stream.Read(buffer, 0, attrib.Length);
//Here the parsing...
}
}
}
当前Read
方法返回void。但我希望它返回bool
,以便可以将类实现为:
var reader = new FixedReader(myStream);
var myData = new MyData();
while (reader.Read()) {}
如何在Read
方法中以及在何处添加EOF检查?