【发布时间】:2013-08-02 20:25:27
【问题描述】:
我正在使用Convert an array of different value types to a byte array 解决方案将我的对象转换为字节数组。
但是我有一个小问题会导致一个大问题。
object[] 中间有“字节”类型的数据,我不知道如何保持“字节”不变。我需要前后保持相同的字节长度。
我尝试将“字节”类型添加到字典中,如下所示:
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);
原来的“字节”变成了字节[2]。
这里发生了什么?在这个解决方案中如何保持字节值的真实性?
谢谢!
【问题讨论】:
-
不清楚这里发生了什么。你能展示创建对象的代码,以及解包它的代码吗?
-
你得到了一个数组,因为
GetBytes返回了一个数组。你到底想在这里做什么,因为不清楚。 -
我更新了我的原始帖子。我知道 GetBytes 返回一个数组,但我希望它返回 byte[1] 作为我的原始字节值。
标签: c# data-conversion