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
参考:
相关用法
- C# DateTimeOffset.Add()用法及代码示例
 - C# String.Contains()用法及代码示例
 - C# Math.Sin()用法及代码示例
 - C# Math.Cos()用法及代码示例
 - C# Dictionary.Add()用法及代码示例
 - C# Math.Tan()用法及代码示例
 - C# Math.Abs()方法用法及代码示例
 - C# Math.Exp()用法及代码示例
 - C# Math.Abs()函数用法及代码示例
 
注:本文由纯净天空筛选整理自rupesh_rao大神的英文原创作品 C# | Random.NextBytes() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
