简体   繁体   English

c#将byte [*,*,*]转换为byte []

[英]c# cast byte[*,*,*] to byte[]

I have an object with a Property of type byte[ , ,*] 我有类型字节的属性的对象[,*]

now i'd like to use System.Random::NextBytes() to fill this multidimensional array with random values. 现在我想使用System.Random :: NextBytes()用随机值填充此多维数组。 NextBytes however takes an argument of byte[] 但是,NextBytes的参数为byte []

can i cast the multidimensional array somehow to the singledimensional one in order to pass it as an argument? 我可以将多维数组以某种方式转换为一维数组以将其作为参数传递吗?

thanks! 谢谢!

You can't cast it, but you can copy the values quickly from a normal byte[] to a byte[,,] using Buffer.BlockCopy . 您无法进行Buffer.BlockCopy ,但是可以使用Buffer.BlockCopy将值从普通的byte[]快速复制到byte[,,] So you'll have to allocate a normal byte array to start with, then copy the results over. 因此,您必须先分配一个普通的字节数组,然后将结果复制过来。

Sample: 样品:

using System;

class Test
{
    static void Main()
    {
        Random rng = new Random();
        byte[,,] y = new byte[2,2,2];
        FillArray(y, rng);

        foreach (byte b in y)
        {
            Console.WriteLine(b);
        }
    }

    static void FillArray(byte[,,] array, Random rng)
    {
        byte[] tmp = new byte[array.Length];
        rng.NextBytes(tmp);
        Buffer.BlockCopy(tmp, 0, array, 0, tmp.Length);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM