简体   繁体   English

C#将object []转换为byte [],但是如何将byte对象保存为byte?

[英]C# convert object[ ] into byte[ ], but how to keep byte object as byte?

I am using Convert an array of different value types to a byte array solution for my objects to byte array conversion. 我正在使用将不同值类型的数组转换为字节数组解决方案,以便我的对象进行字节数组转换。

But I have a small issue that causes a big problem. 但我有一个小问题,导致一个大问题。

There are "byte" type of data in mids of object[], I don't know how to keep "byte" as is. 在object []的mids中有“byte”类型的数据,我不知道如何保持“byte”。 I need keep same bytes-length before and after. 我需要在之前和之后保持相同的字节长度。

I tried add "byte" type into the dictionary like this: 我尝试将“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;
    }
}

there is no syntext complaining, but I traced this code, after the program executed 没有syntext抱怨,但我在程序执行后跟踪了这段代码

byte[] obytes = converter(obj);

the original "byte" becomes byte[2]. 原始的“字节”变为字节[2]。

What happens here? 这里发生了什么? How to keep byte value authentic in this solution? 如何在此解决方案中保持字节值可靠?

Thanks! 谢谢!

There is no BitConverter.GetBytes overload that takes a byte , so your code: 没有BitConverter.GetBytes重载需要一个byte ,所以你的代码:

BitConverter.GetBytes((byte) o)

Is being implicitly expanded into the nearest match: BitConverter.GetBytes(short) ( Int16 ), resulting in two bytes. 被隐式扩展为最接近的匹配: BitConverter.GetBytes(short)Int16 ),产生两个字节。 All you need to do is return a single-element byte array, eg like this: 您需要做的就是返回单元素字节数组,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM