📜  C#| Random.NextBytes()方法

📅  最后修改于: 2021-05-29 19:07:51             🧑  作者: Mango

C#中System.Random类的NextBytes(Byte [])方法用于用随机数填充指定字节数组的元素。此方法将字节数组作为参数,并用随机数填充它。

句法:

public virtual void NextBytes (byte[] buffer);

此处, buffer是包含随机数的字节数组。

异常:如果缓冲区null,则此方法将提供ArgumentNullException

下面的程序说明了NextBytes()方法的用法:

范例1:

// C# program to illustrate the
// use of Random.NextBytes Method
using System;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Instantiate random number generator
        Random rand = new Random();
  
        // Instantiate an array of byte
        Byte[] b = new Byte[10];
  
        rand.NextBytes(b);
  
        // Print random numbers in the byte array
        Console.WriteLine("Printing random numbers"+
                              " in the byte array");
  
        for (int i = 0; i < 10; i++)
            Console.WriteLine("{0} -> {1}", i, b[i]);
    }
}
输出:
Printing random numbers in the byte array
0 -> 63
1 -> 166
2 -> 5
3 -> 212
4 -> 114
5 -> 94
6 -> 161
7 -> 4
8 -> 226
9 -> 46

范例2:

// C# program to illustrate the
// use of Random.NextBytes Method
using System;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Instantiate random number generator
        Random rand = new Random();
  
        // Instantiate an array of byte
        Byte[] b = new Byte[10];
  
        rand.NextBytes(b);
  
        // Print random numbers in the byte array
        Console.WriteLine("Printing random numbers"+
                              " in the byte array");
  
        foreach(byte byteValue in b)
            Console.WriteLine("{0}", byteValue);
    }
}
输出:
Printing random numbers in the byte array
98
68
221
160
179
78
172
129
121
179

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.random.nextbytes?view=netframework-4.7.2