我正在使用将不同值类型的数组转换为字节数组的解决方案来将我的对象转换为字节数组。
但是我有一个小问题引起了大问题。
在对象[]中有“byte”类型的数据,我不知道如何将其保留为原样。我需要保持相同的字节数长度。
我尝试像这样将“byte”类型添加到字典中:
private static readonlyDictionary<Type, Func<object, byte[]>> Converters =
new Dictionary<Type, Func<object, byte[]>>()
{
{ typeof(byte), o => BitConverter.GetBytes((byte) o) },
{ typeof(int), o => BitConverter.GetBytes((int) o) },
{ typeof(UInt16), o => BitConverter.GetBytes((UInt16) o) },
...
};
public static void ToBytes(object[] data, byte[] buffer)
{
int offset = 0;
foreach (object obj in data)
{
if (obj == null)
{
// Or do whatever you want
throw new ArgumentException("Unable to convert null values");
}
Func<object, byte[]> converter;
if (!Converters.TryGetValue(obj.GetType(), out converter))
{
throw new ArgumentException("No converter for " + obj.GetType());
}
byte[] obytes = converter(obj);
Buffer.BlockCopy(obytes, 0, buffer, offset, obytes.Length);
offset += obytes.Length;
}
}
没有语法上的抱怨,但我追踪了这段代码,在程序执行后。
byte[] obytes = converter(obj);
原来的“byte”变成了byte [2]。
这里发生了什么?如何在这个解决方案中保持字节值的真实性?
谢谢!
GetBytes
返回一个数组。你在这里究竟想做什么,因为不清楚。 - Mike Perrenoud