當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Random.NextBytes()用法及代碼示例

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

參考:



相關用法


注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 C# | Random.NextBytes() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。