Buffer.BlockCopy - 对象必须是基元数组
Buffer.BlockCopy - Object must be an array of primitives
我正在尝试从二进制文件中读取数据,我可以读取所有数据类型,除非它是一个字符串数组,我收到错误消息“对象必须是一个基元数组”
这里是我的代码出错的地方
binReader.BaseStream.Seek(position, SeekOrigin.Begin);
buff = binReader.ReadBytes(369);
string[,,] MyArray = new string[1000, 4, 4];
Buffer.BlockCopy(buff, 0, MyArray , 0, buff.Length);
知道如何解决这个问题吗?
我们可以在buffer.blockCopy的文档中看到它只适用于原始类型:
ArgumentException
src or dst is not an array of primitives.
从Type.IsPrimitive我们可以看出基本类型是:
The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.
值得注意的是,字符串不是原始类型,因此不能与 blockCopy 一起使用。
由于问题没有描述字符串是如何存储的,因此很难知道如何读取数据。我建议在数据前加上数组大小。那样阅读会是这样的:
public static string[,,] Read3DArray( BinaryReader binReader)
{
var xSize = binReader.ReadInt32();
var ySize = binReader.ReadInt32();
var zSize= binReader.ReadInt32();
var result = new string[xSize, ySize, zSize];
for (int x = 0; x < xSize; x++)
{
for (int y = 0; y < ySize; y++)
{
for (int z = 0; z < zSize; z++)
{
result[x, y, z] = binReader.ReadString();
}
}
}
return result;
}
如果您知道字符串数组的大小,则可以跳过读取 x/y/z 最大值。
我正在尝试从二进制文件中读取数据,我可以读取所有数据类型,除非它是一个字符串数组,我收到错误消息“对象必须是一个基元数组”
这里是我的代码出错的地方
binReader.BaseStream.Seek(position, SeekOrigin.Begin);
buff = binReader.ReadBytes(369);
string[,,] MyArray = new string[1000, 4, 4];
Buffer.BlockCopy(buff, 0, MyArray , 0, buff.Length);
知道如何解决这个问题吗?
我们可以在buffer.blockCopy的文档中看到它只适用于原始类型:
ArgumentException
src or dst is not an array of primitives.
从Type.IsPrimitive我们可以看出基本类型是:
The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.
值得注意的是,字符串不是原始类型,因此不能与 blockCopy 一起使用。
由于问题没有描述字符串是如何存储的,因此很难知道如何读取数据。我建议在数据前加上数组大小。那样阅读会是这样的:
public static string[,,] Read3DArray( BinaryReader binReader)
{
var xSize = binReader.ReadInt32();
var ySize = binReader.ReadInt32();
var zSize= binReader.ReadInt32();
var result = new string[xSize, ySize, zSize];
for (int x = 0; x < xSize; x++)
{
for (int y = 0; y < ySize; y++)
{
for (int z = 0; z < zSize; z++)
{
result[x, y, z] = binReader.ReadString();
}
}
}
return result;
}
如果您知道字符串数组的大小,则可以跳过读取 x/y/z 最大值。