【问题标题】:C# convert object[ ] into byte[ ], but how to keep byte object as byte?C# 将 object[ ] 转换为 byte[ ],但是如何将 byte 对象保留为 byte?
【发布时间】: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


【解决方案1】:

没有采用byteBitConverter.GetBytes 重载,因此您的代码:

BitConverter.GetBytes((byte) o)

被隐式扩展为最近的匹配:BitConverter.GetBytes(short) (Int16),产生两个字节。您需要做的就是返回一个单元素字节数组,例如像这样:

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

【讨论】:

  • 谢谢大家。有用。我不明白这个 lambda 的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 2020-02-03
  • 2014-07-21
  • 1970-01-01
  • 2018-03-25
  • 2012-02-05
相关资源
最近更新 更多