在C#中,可以使用反射和Marshal类来将字节数组转换为具有未知类型的基本类型数组。以下是一个示例代码:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
public class ByteArrayToArrayConverter
{
public static Array ConvertToArray(byte[] byteArray, Type elementType, int elementCount)
{
// 创建一个基本类型数组
Array array = Array.CreateInstance(elementType, elementCount);
// 将字节数组转换为基本类型数组
GCHandle handle = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(byteArray, 0);
Marshal.Copy(ptr, array, 0, elementCount);
handle.Free();
return array;
}
}
在上面的代码中,ConvertToArray
方法接受一个字节数组、一个元素类型和一个元素数量作为参数。它首先创建一个基本类型数组,然后使用GCHandle
和Marshal
类将字节数组转换为基本类型数组。最后,它返回转换后的数组。
以下是一个使用示例:
byte[] byteArray = new byte[] { 1, 2, 3, 4, 5 };
Array intArray = ByteArrayToArrayConverter.ConvertToArray(byteArray, typeof(int), 5);
foreach (int i in intArray)
{
Console.WriteLine(i);
}
在上面的示例中,我们将一个包含5个字节的字节数组转换为一个整数数组,并将其打印出来。
领取专属 10元无门槛券
手把手带您无忧上云