C#将object[]转换为byte[],但如何将byte object保持为byte?
我正在使用对象到字节数组转换的解决方案 但我有一个小问题导致了一个大问题 对象[]的mids中有“字节”类型的数据,我不知道如何保持“字节”不变。我需要在前后保持相同的字节长度 我尝试将“byte”类型添加到字典中,如下所示:C#将object[]转换为byte[],但如何将byte object保持为byte?,c#,data-conversion,C#,Data Conversion,我正在使用对象到字节数组转换的解决方案 但我有一个小问题导致了一个大问题 对象[]的mids中有“字节”类型的数据,我不知道如何保持“字节”不变。我需要在前后保持相同的字节长度 我尝试将“byte”类型添加到字典中,如下所示: private static readonlyDictionary<Type, Func<object, byte[]>> Converters = new Dictionary<Type, Func<object, 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;
}
}
{ typeof(byte), o => new[] { (byte) o } }
原始“字节”变为字节[2]
这里发生了什么?如何在此解决方案中保持字节值的真实性
谢谢 没有占用字节的重载,因此您的代码:
BitConverter.GetBytes((byte) o)
正在隐式展开为最接近的匹配:(Int16
),结果是两个字节。您只需返回一个单元素字节数组,例如:
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;
}
}
{ typeof(byte), o => new[] { (byte) o } }
现在还不清楚这里发生了什么。您可以显示创建对象的代码以及解压对象的代码吗?您将获得一个数组,因为GetBytes
返回一个数组。因为不清楚,你到底想在这里做什么。我更新了我的原始帖子。我知道GetBytes返回一个数组,但我希望它返回字节[1]作为我的原始字节值。谢谢大家。它起作用了。我不明白这件事。