Initialize a byte array to a certain value, other than the default null?

This question already has an answer here:

  • What is the equivalent of memset in C#? 13 answers

  • For small arrays use array initialisation syntax:

    var sevenItems = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
    

    For larger arrays use a standard for loop. This is the most readable and efficient way to do it:

    var sevenThousandItems = new byte[7000];
    for (int i = 0; i < sevenThousandItems.Length; i++)
    {
        sevenThousandItems[i] = 0x20;
    }
    

    Of course, if you need to do this a lot then you could create a helper method to help keep your code concise:

    byte[] sevenItems = CreateSpecialByteArray(7);
    byte[] sevenThousandItems = CreateSpecialByteArray(7000);
    
    // ...
    
    public static byte[] CreateSpecialByteArray(int length)
    {
        var arr = new byte[length];
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = 0x20;
        }
        return arr;
    }
    

    Use this to create the array in the first place:

    byte[] array = Enumerable.Repeat((byte)0x20, <number of elements>).ToArray();
    

    Replace <number of elements> with the desired array size.


    You can use Enumerable.Repeat()

    Array of 100 items initialized to 0x20:

    byte[] arr1 = Enumerable.Repeat(0x20,100).ToArray();
    
    链接地址: http://www.djcxy.com/p/31492.html

    上一篇: 私人与受保护

    下一篇: 将字节数组初始化为某个值,而不是默认的空值?