【发布时间】:2017-05-10 18:53:30
【问题描述】:
我正在解析一个字节数组,其中包含以固定格式存储的不同类型值。例如,前 4 个字节可能是一个包含数组大小的 int - 假设双精度数组,所以接下来的 8 个字节代表一个双精度 - 数组的第一个元素等。理论上它可以包含其他类型的值,但假设我们只能有 bool,int,uint,short,ushort,long,ulong,float,double 和其中每一个的数组。简单的方法:
public class FixedFormatParser
{
private byte[] _Contents;
private int _CurrentPos = 0;
public FixedFormatParser(byte[] contents)
{
_Contents = contents;
}
bool ReadBool()
{
bool res = BitConverter.ToBoolean(_Contents, _CurrentPos);
_CurrentPos += sizeof(bool);
return res;
}
int ReadInt()
{
int res = BitConverter.ToInt32(_Contents, _CurrentPos);
_CurrentPos += sizeof(int);
return res;
}
// etc. for uint, short, ushort, long, ulong, float, double
int[] ReadIntArray()
{
int size = ReadInt();
if (size == 0)
return null;
int[] res = new int[size];
for (int i = 0; i < size; i++)
res[i] = ReadInt();
return res;
}
// etc. for bool, uint, short, ushort, long, ulong, float, double
}
我显然可以编写 18 种方法来涵盖每种情况,但似乎应该有一种方法来概括这一点。
bool val = Read<bool>();
long[] arr = ReadArray<long>(); // or ReadArray(Read<long>);
显然,我并不是说除了 18 种方法之外还要编写 2 个包装器来支持这种语法。语法并不重要,代码重复才是问题所在。另一个考虑因素是性能。理想情况下,不会有任何(或很多)性能影响。谢谢。
更新:
关于其他被认为是重复的问题。我不同意,因为他们都没有解决我所追求的特定概括,但其中一个非常接近: 中的第一个答案 C# Reading Byte Array 描述了包装 BinaryReader。这将涵盖 18 种方法中的 9 种。这样就解决了一半的问题。我仍然需要编写所有各种数组读取。
public class FixedFormatParser2 : BinaryReader
{
public FixedFormatParser2(byte[] input) : base(new MemoryStream(input))
{
}
public override string ReadString()
{
//
}
public double[] ReadDoubleArray()
{
int size = ReadInt32();
if (size == 0)
return null;
double[] res = new double[size];
for (int i = 0; i < size; i++)
res[i] = ReadDouble();
return res;
}
}
如何不为每种类型编写单独的 ReadXXXArray?
离我最近的地方:
public void WriteCountedArray(dynamic[] input)
{
if (input == null || input.Length == 0)
Write((int)0);
else
{
Write(input.Length);
foreach (dynamic val in input)
Write(val);
}
}
这样可以编译,但调用它很麻烦而且很昂贵:
using (FixedFormatWriter writer = new FixedFormatWriter())
{
double[] array = new double[3];
// ... assign values
writer.WriteCountedArray(array.Select(x=>(dynamic)x).ToArray());
【问题讨论】:
-
我没有尝试做你正在做的事情,但是is this question helpful?
-
StriplingWarrior - 我确实费心让你的建议发挥作用。一个工作示例的更好链接是stackoverflow.com/questions/2623761/… 这种方法的问题是它既昂贵又麻烦,以至于我更喜欢代码重复。但是是的,它在技术上确实符合我的要求。