Random.NextBytes 方法

定義

多載

NextBytes(Span<Byte>)

以亂數填入指定位元組範圍的元素。

NextBytes(Byte[])

以亂數填入指定位元組陣列的元素。

NextBytes(Span<Byte>)

來源:
Random.cs
來源:
Random.cs
來源:
Random.cs

以亂數填入指定位元組範圍的元素。

public:
 virtual void NextBytes(Span<System::Byte> buffer);
public virtual void NextBytes (Span<byte> buffer);
abstract member NextBytes : Span<byte> -> unit
override this.NextBytes : Span<byte> -> unit
Public Overridable Sub NextBytes (buffer As Span(Of Byte))

參數

buffer
Span<Byte>

要填入亂數的陣列。

備註

位元組範圍的每個元素都會設定為大於或等於 0 且小於或等於 MaxValue 的亂數。

適用於

NextBytes(Byte[])

來源:
Random.cs
來源:
Random.cs
來源:
Random.cs

以亂數填入指定位元組陣列的元素。

public:
 virtual void NextBytes(cli::array <System::Byte> ^ buffer);
public virtual void NextBytes (byte[] buffer);
abstract member NextBytes : byte[] -> unit
override this.NextBytes : byte[] -> unit
Public Overridable Sub NextBytes (buffer As Byte())

參數

buffer
Byte[]

要填入亂數的陣列。

例外狀況

buffernull

範例

下列範例示範如何使用 NextBytes 方法,以隨機位元組值填入位元組陣列。

#using <System.DLL>

using namespace System;

void main()
{
   Random^ rnd = gcnew Random;
   array<unsigned char>^b = gcnew array<unsigned char>(10);
   rnd->NextBytes( b );
   Console::WriteLine("The Random bytes are:");
   for ( int i = 0; i < 10; i++ )
      Console::WriteLine("{0}: {1}", i, b[i]);
}
// The example displays output similar to the following:
//       The Random bytes are:
//       0: 131
//       1: 96
//       2: 226
//       3: 213
//       4: 176
//       5: 208
//       6: 99
//       7: 89
//       8: 226
//       9: 194
Random rnd = new Random();
Byte[] b = new Byte[10];
rnd.NextBytes(b);
Console.WriteLine("The Random bytes are: ");
for (int i = 0; i <= b.GetUpperBound(0); i++)
    Console.WriteLine("{0}: {1}", i, b[i]);

// The example displays output similar to the following:
//       The Random bytes are:
//       0: 131
//       1: 96
//       2: 226
//       3: 213
//       4: 176
//       5: 208
//       6: 99
//       7: 89
//       8: 226
//       9: 194
Public Class Example
    Public Shared Sub Main()
        Dim rnd As New Random()
        Dim b(9) As Byte
        rnd.NextBytes(b)
        Console.WriteLine("The Random bytes are: ")
        For i As Integer = 0 To b.GetUpperBound(0)
            Console.WriteLine("{0}: {1}", i, b(i))
        Next
    End Sub 
End Class 
' The example displays output similar to the following:
'       The Random bytes are:
'       0: 131
'       1: 96
'       2: 226
'       3: 213
'       4: 176
'       5: 208
'       6: 99
'       7: 89
'       8: 226
'       9: 194

備註

位元組陣列的每個元素都會設定為大於或等於 0 的亂數,且小於或等於 MaxValue

例如,若要產生適合建立隨機密碼的密碼編譯保護亂數,請使用 之類的 RNGCryptoServiceProvider.GetBytes 方法。

給繼承者的注意事項

從 .NET Framework 2.0 版開始,如果您從 Random 衍生類別並覆 Sample() 寫 方法,則方法衍生類別實 Sample() 作所提供的散發不會用於呼叫 方法的基類實作 NextBytes(Byte[]) 。 相反地,會使用基 Random 類所傳回的統一分佈。 此行為可改善 類別的整體效能 Random 。 若要修改此行為以呼叫 Sample() 衍生類別中的 方法,您也必須覆寫 NextBytes(Byte[]) 方法。

另請參閱

適用於