创建字节数组重构

时间:2015-08-20 14:36:57

标签: c# .net bytearray

我需要创建用于测试的字节数组。我实现了自己的解决方案,但不确定它是否是最佳的。这是:

byte counter = 0;
Func<int, byte[]> createByteArray = size =>
{
    var array = new byte[size];
    for (int index = 0; index < size; index++)
    {
        array[index] = counter++;

        if (counter == byte.MaxValue)
        {
            counter = 0;
        }
    }
    return array;
};

有没有办法简化这个?

3 个答案:

答案 0 :(得分:4)

我不确定这是否更好,但更短。

Func<int, byte[]> createByteArray = size => Enumerable.Range(0, size)
                                            .Select(i => (byte)(i % 256))
                                            .ToArray();

答案 1 :(得分:1)

由于它是用于测试的,您可以使用Random.NextBytes(...)创建一个完整的随机缓冲区。

如果没有,你不需要分支机构:

Func<int, byte[]> createByteArray = size =>
{
    var array = new byte[size];
    for (int index = 0; index < size; index++)
    {
        array[index] = (byte)(index & 0xFF);
    }
    return array;
};

答案 2 :(得分:0)

你有C#!用它!

byte counter = 0;
Func<int, byte[]> createByteArray = size =>
{
    var array = new byte[size];
    for (int index = 0; index < size; index++)
    {
        unchecked 
        {
            array[index] = counter++;
        }
    }
    return array;
};

不确定为什么外面有counter。但如果你喜欢这种方式......

使用unchecked块允许数字溢出。这会将您的价值限制为byte范围内的可能值。

我不知道您生成的阵列有多大。如果生成速度是一个问题并且数组非常大,那么您只能手动填充值0到255,然后完成开始将卡盘复制到剩余的数组中。有关此信息,请参阅Array.ConstrainedCopy。但这只有在数组生成太慢且数组非常大(n字节范围的n倍)时才有意义