在C#中将字节数组转换为具有未知类型的基本类型数组

Wil*_*sem 5 .net c# bytearray primitive-types

我有以下问题.我有一个字节数组,我想转换介绍一个基本类型的数组.但我不知道这种类型.(这是一个类型的数组).结果我需要一个对象数组.

当然我可以在类型上使用开关(只有有限数量),但我想知道是否有更好的解决方案.

例:

byte[] byteData = new byte[] {0xa0,0x14,0x72,0xbf,0x72,0x3c,0x21}
Type[] types = new Type[] {typeof(int),typeof(short),typeof(sbyte)};

//some algorithm

object[] primitiveData = {...};
//this array contains an the following elements
//an int converted from 0xa0,0x14,0x72,0xbf
//a short converted from 0x72, 0x3c
//a sbyte converted from 0x21
Run Code Online (Sandbox Code Playgroud)

是否有算法或我应该使用开关

Mik*_*son 3

这段代码使用 unsafe 来获取指向字节数组缓冲区的指针,但这应该不是问题。

[编辑-评论后更改代码]

byte[] byteData = new byte[] { 0xa0, 0x14, 0x72, 0xbf, 0x72, 0x3c, 0x21 };
Type[] types = new Type[] { typeof(int), typeof(short), typeof(sbyte) };

object[] result = new object[types.Length];
unsafe
{
    fixed (byte* p = byteData)
    {
        var localPtr = p;
        for (int i = 0; i < types.Length; i++)
        {
            result[i] = Marshal.PtrToStructure((IntPtr)localPtr, types[i]);
            localPtr += Marshal.SizeOf(types[i]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)