Random 建構函式

定義

初始化 Random 類別的新執行個體。

多載

Random()

使用預設種子值初始化 Random 類別的新執行個體。

Random(Int32)

使用指定的種子值,初始化 Random 類別的新執行個體。

Random()

使用預設種子值初始化 Random 類別的新執行個體。

public:
 Random();
public Random ();
Public Sub New ()

範例

下列範例會使用無參數的函式來具現化三個 Random 物件,並顯示每個物件的五個隨機整數序列。 如果是在 .NET Framework 上執行,因為前兩個 Random 物件會以系統時鐘為基礎,使用相同的種子值進行具現化,因此會產生相同的亂數序列。 另一方面,第三個物件的無參數的函 Random 式會在呼叫方法所造成的兩秒延遲後呼叫 Thread.Sleep 。 因為這會為第三個物件產生不同的種子值 Random ,所以會產生不同的亂數字序列。

using System;
using System.Threading;

public class RandomNumbers
{
   public static void Main()
   {
      Random rand1 = new Random();
      Random rand2 = new Random();
      Thread.Sleep(2000);
      Random rand3 = new Random();
      ShowRandomNumbers(rand1);
      ShowRandomNumbers(rand2);
      ShowRandomNumbers(rand3);
   }

   private static void ShowRandomNumbers(Random rand)
   {
      Console.WriteLine();
      byte[] values = new byte[5];
      rand.NextBytes(values);
      foreach (byte value in values)
         Console.Write("{0, 5}", value);
      Console.WriteLine();
   }
}
// The example displays an output similar to the following:
//       28   35  133  224   58
//
//       28   35  133  224   58
//
//       32  222   43  251   49
open System
open System.Threading

let showRandomNumbers (rand: Random) =
    printfn ""
    let values = Array.zeroCreate 5
    rand.NextBytes values
    for value in values do 
        printf "%5i" value
    printfn ""

let rand1 = Random()
let rand2 = Random()
Thread.Sleep 2000
let rand3 = Random()

showRandomNumbers rand1
showRandomNumbers rand2
showRandomNumbers rand3

// The example displays an output similar to the following:
//       28   35  133  224   58
//
//       28   35  133  224   58
//
//       32  222   43  251   49
Imports System.Threading

Module RandomNumbers
   Public Sub Main()
      Dim rand1 As New Random()
      Dim rand2 As New Random()
      Thread.Sleep(2000)
      Dim rand3 As New Random()
      ShowRandomNumbers(rand1)
      ShowRandomNumbers(rand2)
      ShowRandomNumbers(rand3)
   End Sub
   
   Private Sub ShowRandomNumbers(rand As Random)
      Console.WriteLine()
      Dim values(4) As Byte
      rand.NextBytes(values)
      For Each value As Byte In values
         Console.Write("{0, 5}", value)
      Next      
      Console.WriteLine() 
   End Sub
End Module
' The example displays an output similar to the following:
'       28   35  133  224   58
'    
'       28   35  133  224   58
'    
'       32  222   43  251   49

備註

在 .NET Framework 中,預設的種子值衍生自系統時鐘,其具有有限的解析。 如此一來, Random 呼叫無參數的函式時,會連續建立不同的物件具有相同的預設種子值,因此會產生相同的亂數組。 您可以使用單一 Random 物件來產生所有亂數,以避免這個問題。 您也可以藉由產生自己的隨機種子值並將它傳遞至函式,來解決此問題 Random(Int32) 。 如需詳細資訊,請參閱函式 Random(Int32)

在 .NET Core 中,預設的種子值是由執行緒靜態的虛擬亂數產生器所產生,因此不適用先前描述的限制。 在關閉時所建立的不同 Random 物件會在 .Net Core 中產生不同組的亂數字。

如果您想要讓亂數產生器產生隨機的數位序列,請呼叫此函式。 若要針對不同的亂數產生器產生固定的亂數序列,請使用固定的種子值來呼叫此函式 Random(Int32)Random測試使用亂數字的應用程式時,經常會使用這個函式多載。

當您具現化亂數產生器之後,您可以呼叫個別 Random 方法(例如 Next()NextDouble() )來產生亂數字。

適用於

Random(Int32)

使用指定的種子值,初始化 Random 類別的新執行個體。

public:
 Random(int Seed);
public Random (int Seed);
new Random : int -> Random
Public Sub New (Seed As Integer)

參數

Seed
Int32

用來計算虛擬亂數序列起始值的數字。 如果指定了負數,則會採用數字的絕對值。

範例

下列範例會建立具有類別的函式的物件,該函式 Random 會採用種子參數並產生一連串的隨機整數和雙精度浮點數。 此範例說明使用函式 Random 和種子參數再次建立物件時,會產生相同的順序。

// Example of the Random class constructors and Random::NextDouble() 
// method.
using namespace System;
using namespace System::Threading;

// Generate random numbers from the specified Random object.
void RunIntNDoubleRandoms(Random^ randObj)
{
   
   // Generate the first six random integers.
   for (int j = 0; j < 6; j++)
      Console::Write(" {0,10} ", randObj->Next());
   Console::WriteLine();
   
   // Generate the first six random doubles.
   for (int j = 0; j < 6; j++)
      Console::Write(" {0:F8} ", randObj->NextDouble());
   Console::WriteLine();
}


// Create a Random object with the specified seed.
void FixedSeedRandoms(int seed)
{
   Console::WriteLine("\nRandom numbers from a Random object with seed = {0}:", seed);
   Random^ fixRand = gcnew Random(seed);
   RunIntNDoubleRandoms(fixRand);
}


// Create a random object with a timer-generated seed.
void AutoSeedRandoms()
{
   
   // Wait to allow the timer to advance.
   Thread::Sleep(1);
   Console::WriteLine("\nRandom numbers from a Random object "
   "with an auto-generated seed:");
   Random^ autoRand = gcnew Random;
   RunIntNDoubleRandoms(autoRand);
}

int main()
{
   Console::WriteLine("This example of the Random class constructors and Random"
   "::NextDouble() \ngenerates the following output.\n");
   Console::WriteLine("Create Random objects, and then generate and "
   "display six integers and \nsix doubles from each.");
   FixedSeedRandoms(123);
   FixedSeedRandoms(123);
   FixedSeedRandoms(456);
   FixedSeedRandoms(456);
   AutoSeedRandoms();
   AutoSeedRandoms();
   AutoSeedRandoms();
}

/*
This example of the Random class constructors and Random::NextDouble()
generates an output similar to the following:

Create Random objects, and then generate and display six integers and
six doubles from each.

Random numbers from a Random object with seed = 123:
 2114319875  1949518561  1596751841  1742987178  1586516133   103755708
 0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146

Random numbers from a Random object with seed = 123:
 2114319875  1949518561  1596751841  1742987178  1586516133   103755708
 0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146

Random numbers from a Random object with seed = 456:
 2044805024  1323311594  1087799997  1907260840   179380355   120870348
 0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170

Random numbers from a Random object with seed = 456:
 2044805024  1323311594  1087799997  1907260840   179380355   120870348
 0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170

Random numbers from a Random object with an auto-generated seed:
 1624372556  1894939458   302472229   588108304    23919954  1085111949
 0.14595512  0.30162298  0.92267372  0.55707657  0.25430079  0.74143239

Random numbers from a Random object with an auto-generated seed:
 2105952511  1753605347   280739490   876793040  1129567796   524571616
 0.62652210  0.31846701  0.15984073  0.24458755  0.62160607  0.54857684

Random numbers from a Random object with an auto-generated seed:
  440048819  1612271236   259006751  1165477776    87731991  2111514930
 0.10708907  0.33531104  0.39700773  0.93209853  0.98891135  0.35572129
*/
// Example of the Random class constructors and Random.NextDouble()
// method.
using System;
using System.Threading;

public class RandomObjectDemo
{
    // Generate random numbers from the specified Random object.
    static void RunIntNDoubleRandoms(Random randObj)
    {
        // Generate the first six random integers.
        for(int j = 0; j < 6; j++)
            Console.Write(" {0,10} ", randObj.Next());
        Console.WriteLine();

        // Generate the first six random doubles.
        for(int j = 0; j < 6; j++)
            Console.Write(" {0:F8} ", randObj.NextDouble());
        Console.WriteLine();
    }

    // Create a Random object with the specified seed.
    static void FixedSeedRandoms(int seed)
    {
        Console.WriteLine(
            "\nRandom numbers from a Random object with " +
            "seed = {0}:", seed);
        Random fixRand = new Random(seed);

        RunIntNDoubleRandoms(fixRand);
    }

    // Create a random object with a timer-generated seed.
    static void AutoSeedRandoms()
    {
        // Wait to allow the timer to advance.
        Thread.Sleep(1);

        Console.WriteLine(
            "\nRandom numbers from a Random object " +
            "with an auto-generated seed:");
        Random autoRand = new Random();

        RunIntNDoubleRandoms(autoRand);
    }

    static void Main()
    {	
        Console.WriteLine(
            "This example of the Random class constructors and " +
            "Random.NextDouble() \n" +
            "generates the following output.\n");
        Console.WriteLine(
            "Create Random objects, and then generate and " +
            "display six integers and \nsix doubles from each.");

        FixedSeedRandoms(123);
        FixedSeedRandoms(123);

        FixedSeedRandoms(456);
        FixedSeedRandoms(456);

        AutoSeedRandoms();
        AutoSeedRandoms();
        AutoSeedRandoms();
    }
}

/*
This example of the Random class constructors and Random.NextDouble()
generates an output similar to the following:

Create Random objects, and then generate and display six integers and
six doubles from each.

Random numbers from a Random object with seed = 123:
 2114319875  1949518561  1596751841  1742987178  1586516133   103755708
 0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146

Random numbers from a Random object with seed = 123:
 2114319875  1949518561  1596751841  1742987178  1586516133   103755708
 0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146

Random numbers from a Random object with seed = 456:
 2044805024  1323311594  1087799997  1907260840   179380355   120870348
 0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170

Random numbers from a Random object with seed = 456:
 2044805024  1323311594  1087799997  1907260840   179380355   120870348
 0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170

Random numbers from a Random object with an auto-generated seed:
  380213349   127379247  1969091178  1983029819  1963098450  1648433124
 0.08824121  0.41249688  0.36445811  0.05637512  0.62702451  0.49595560

Random numbers from a Random object with an auto-generated seed:
  861793304  2133528783  1947358439   124230908   921262645  1087892791
 0.56880819  0.42934091  0.60162512  0.74388610  0.99432979  0.30310005

Random numbers from a Random object with an auto-generated seed:
 1343373259  1992194672  1925625700   412915644  2026910487   527352458
 0.04937517  0.44618494  0.83879212  0.43139707  0.36163507  0.11024451
*/
// Example of the Random class constructors and Random.NextDouble()
// method.
open System
open System.Threading

// Generate random numbers from the specified Random object.
let runIntNDoubleRandoms (randObj: Random) =
    // Generate the first six random integers.
    for _ = 1 to 6 do
        printf $" {randObj.Next(),10} "
    printfn ""

    // Generate the first six random doubles.
    for _ = 1 to 6 do
        printf $" {randObj.NextDouble():F8} "
    printfn ""

let fixedSeedRandoms seed =
    printfn $"\nRandom numbers from a Random object with seed = %i{seed}:"
    let fixRand = Random seed
    
    runIntNDoubleRandoms fixRand

let autoSeedRandoms () =
    // Wait to allow the timer to advance.
    Thread.Sleep 1

    printfn "\nRandom numbers from a Random object with an auto-generated seed: "
    let autoRand = Random ()

    runIntNDoubleRandoms autoRand

printfn 
  """This example of the Random class constructors and Random.NextDouble()
generates the following output.
Create Random objects, and then generate and display six integers and
six doubles from each."""
 
fixedSeedRandoms 123
fixedSeedRandoms 123

fixedSeedRandoms 456
fixedSeedRandoms 456

autoSeedRandoms ()
autoSeedRandoms ()
autoSeedRandoms ()

(*
This example of the Random class constructors and Random.NextDouble()
generates an output similar to the following:

Create Random objects, and then generate and display six integers and
six doubles from each.

Random numbers from a Random object with seed = 123:
 2114319875  1949518561  1596751841  1742987178  1586516133   103755708
 0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146

Random numbers from a Random object with seed = 123:
 2114319875  1949518561  1596751841  1742987178  1586516133   103755708
 0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146

Random numbers from a Random object with seed = 456:
 2044805024  1323311594  1087799997  1907260840   179380355   120870348
 0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170

Random numbers from a Random object with seed = 456:
 2044805024  1323311594  1087799997  1907260840   179380355   120870348
 0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170

Random numbers from a Random object with an auto-generated seed:
  380213349   127379247  1969091178  1983029819  1963098450  1648433124
 0.08824121  0.41249688  0.36445811  0.05637512  0.62702451  0.49595560

Random numbers from a Random object with an auto-generated seed:
  861793304  2133528783  1947358439   124230908   921262645  1087892791
 0.56880819  0.42934091  0.60162512  0.74388610  0.99432979  0.30310005

Random numbers from a Random object with an auto-generated seed:
 1343373259  1992194672  1925625700   412915644  2026910487   527352458
 0.04937517  0.44618494  0.83879212  0.43139707  0.36163507  0.11024451
*)
' Example of the Random class constructors and Random.NextDouble() 
' method.
Imports System.Threading

Module RandomObjectDemo

    ' Generate random numbers from the specified Random object.
    Sub RunIntNDoubleRandoms(randObj As Random)

        ' Generate the first six random integers.
        Dim j As Integer
        For j = 0 To 5
            Console.Write(" {0,10} ", randObj.Next())
        Next j
        Console.WriteLine()
            
        ' Generate the first six random doubles.
        For j = 0 To 5
            Console.Write(" {0:F8} ", randObj.NextDouble())
        Next j
        Console.WriteLine()
    End Sub 
        
    ' Create a Random object with the specified seed.
    Sub FixedSeedRandoms(seed As Integer)

        Console.WriteLine(vbCrLf & _
            "Random numbers from a Random object with " & _
            "seed = {0}:", seed)
        Dim fixRand As New Random(seed)
            
        RunIntNDoubleRandoms(fixRand)
    End Sub 
        
    ' Create a random object with a timer-generated seed.
    Sub AutoSeedRandoms()

        ' Wait to allow the timer to advance.
        Thread.Sleep(1)
            
        Console.WriteLine(vbCrLf & _
            "Random numbers from a Random object " & _ 
            "with an auto-generated seed:")
        Dim autoRand As New Random()
            
        RunIntNDoubleRandoms(autoRand)
    End Sub 
        
    Sub Main()
        Console.WriteLine(_
            "This example of the Random class constructors " & _
            "and Random.NextDouble() " & vbCrLf & _
            "generates the following output." & vbCrLf)
        Console.WriteLine("Create Random " & _
            "objects, and then generate and display six " & _
            "integers and " & vbCrLf & "six doubles from each.")
            
        FixedSeedRandoms(123)
        FixedSeedRandoms(123)
            
        FixedSeedRandoms(456)
        FixedSeedRandoms(456)
            
        AutoSeedRandoms()
        AutoSeedRandoms()
        AutoSeedRandoms()
    End Sub
End Module 

' This example of the Random class constructors and Random.NextDouble()
' generates an output similar to the following:
' 
' Create Random objects, and then generate and display six integers and
' six doubles from each.
' 
' Random numbers from a Random object with seed = 123:
'  2114319875  1949518561  1596751841  1742987178  1586516133   103755708
'  0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146
' 
' Random numbers from a Random object with seed = 123:
'  2114319875  1949518561  1596751841  1742987178  1586516133   103755708
'  0.01700087  0.14935942  0.19470390  0.63008947  0.90976122  0.49519146
' 
' Random numbers from a Random object with seed = 456:
'  2044805024  1323311594  1087799997  1907260840   179380355   120870348
'  0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170
' 
' Random numbers from a Random object with seed = 456:
'  2044805024  1323311594  1087799997  1907260840   179380355   120870348
'  0.21988117  0.21026556  0.39236514  0.42420498  0.24102703  0.47310170
' 
' Random numbers from a Random object with an auto-generated seed:
'  1920831619  1346865774  2006582766  1968819760   332463652   110770792
'  0.71326689  0.50383335  0.50446082  0.66312569  0.94517193  0.58059287
' 
' Random numbers from a Random object with an auto-generated seed:
'   254927927  1205531663  1984850027   110020849  1438111494  1697714106
'  0.19383387  0.52067738  0.74162783  0.35063667  0.31247720  0.38773733
' 
' Random numbers from a Random object with an auto-generated seed:
'   736507882  1064197552  1963117288   398705585   396275689  1137173773
'  0.67440084  0.53752140  0.97879483  0.03814764  0.67978248  0.19488178

備註

將相同的種子值提供給不同的 Random 物件,會導致每個實例產生相同的亂數字序列。 當測試依賴亂數產生器的應用程式時,通常會執行這項操作。

如果您的應用程式需要不同的亂數序列,請使用不同的種子值重複叫用此函式。 產生唯一種子值的其中一種方式,是讓它與時間相依。 例如,從系統時鐘衍生種子值,因為多載會這樣 Random() 做。 不過,系統時鐘可能沒有足夠的解析度,無法使用不同的種子值來提供此函式的不同調用。 在 .NET Framework 上,這會產生亂數產生器,以產生相同的虛擬亂數序列,如下列範例中的前兩個 Random 物件所示。 若要避免這種情況,請套用演算法來區分每個調用中的種子值,或呼叫 Thread.Sleep 方法以確保您提供每個具有不同種子值的函式。

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Random rand1 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
      Random rand2 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
      Thread.Sleep(20);
      Random rand3 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
      ShowRandomNumbers(rand1);
      ShowRandomNumbers(rand2);
      ShowRandomNumbers(rand3);
   }

   private static void ShowRandomNumbers(Random rand)
   {
      Console.WriteLine();
      byte[] values = new byte[4];
      rand.NextBytes(values);
      foreach (var value in values)
         Console.Write("{0, 5}", value);

      Console.WriteLine();
   }
}
// The example displays output similar to the following:
//   145  214  177  134  173
//
//   145  214  177  134  173
//
//   126  185  175  249  157
open System
open System.Threading

let showRandomNumbers (rand: Random) =
    printfn ""
    let values = Array.zeroCreate 5
    rand.NextBytes values
    for value in values do 
        printf "%5i" value
    printfn ""

let rand1 = Random(DateTime.Now.Ticks &&& 0x0000FFFFL |> int)
let rand2 = Random(DateTime.Now.Ticks &&& 0x0000FFFFL |> int)
Thread.Sleep 20
let rand3 = Random(DateTime.Now.Ticks &&& 0x0000FFFFL |> int)

showRandomNumbers rand1
showRandomNumbers rand2
showRandomNumbers rand3

// The example displays output similar to the following:
//   145  214  177  134  173
//
//   145  214  177  134  173
//
//   126  185  175  249  157
Imports System.Threading

Module RandomNumbers
   Public Sub Main()
      Dim rand1 As New Random(CInt(Date.Now.Ticks And &h0000FFFF))
      Dim rand2 As New Random(CInt(Date.Now.Ticks And &h0000FFFF))
      Thread.Sleep(20)
      Dim rand3 As New Random(CInt(Date.Now.Ticks And &h0000FFFF))
      ShowRandomNumbers(rand1)
      ShowRandomNumbers(rand2)
      ShowRandomNumbers(rand3)
   End Sub
   
   Private Sub ShowRandomNumbers(rand As Random)
      Console.WriteLine()
      Dim values(4) As Byte
      rand.NextBytes(values)
      For Each value As Byte In values
         Console.Write("{0, 5}", value)
      Next      
      Console.WriteLine() 
   End Sub
End Module
' The example displays output similar to the following:
'      145  214  177  134  173
'    
'      145  214  177  134  173
'    
'      126  185  175  249  157

另一個選項是將 Random 用來產生應用程式中所有亂數字的單一物件具現化。 這會產生稍微更好的效能,因為具現化亂數產生器相當昂貴。

適用於