Random.NextBytes 方法  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
重载
| NextBytes(Span<Byte>) | 用随机数填充指定字节范围的元素。 | 
| NextBytes(Byte[]) | 用随机数填充指定字节数组的元素。 | 
NextBytes(Span<Byte>)
- Source:
- Random.cs
- Source:
- Random.cs
- Source:
- 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> -> unitPublic Overridable Sub NextBytes (buffer As Span(Of Byte))参数
注解
字节范围的每个元素都设置为大于或等于 0 且小于或等于 MaxValue的随机数。
适用于
NextBytes(Byte[])
- Source:
- Random.cs
- Source:
- Random.cs
- Source:
- 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[] -> unitPublic Overridable Sub NextBytes (buffer As Byte())参数
- buffer
- Byte[]
要用随机数填充的数组。
例外
              buffer 上声明的默认值为 null。
示例
以下示例演示如何使用 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[]) 方法。