将C#对象数组转换为字节数组,但如何将字节对象保留为字节?

7
我正在使用将不同值类型的数组转换为字节数组的解决方案来将我的对象转换为字节数组。

但是我有一个小问题引起了大问题。

在对象[]中有“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]。

这里发生了什么?如何在这个解决方案中保持字节值的真实性?

谢谢!


1
这里发生了什么并不清楚。你能展示一下创建对象的代码以及解包它的代码吗? - cdhowie
你得到了一个数组,因为GetBytes返回一个数组。你在这里究竟想做什么,因为不清楚。 - Mike Perrenoud
我更新了我的原始帖子。我知道GetBytes返回一个数组,但我想让它返回byte [1]以获取我的原始字节值。 - Kai Mon
1个回答

15

没有接受byte类型参数的 BitConverter.GetBytes 重载方法,因此您的代码:

BitConverter.GetBytes((byte) o)

该方法被隐式扩展为最接近的匹配项:BitConverter.GetBytes(short) (Int16),结果为两个字节。你只需要返回一个单元素的字节数组,就像这样:

{ typeof(byte), o => new[] { (byte) o } }

谢谢大家,它确实有效。我不理解这个lambda的东西。 - Kai Mon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接