Random 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
代表一種偽隨機數產生器,這是一種產生符合特定統計隨機性要求的數字序列的演算法。
public ref class Random
public class Random
[System.Serializable]
public class Random
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class Random
type Random = class
[<System.Serializable>]
type Random = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Random = class
Public Class Random
- 繼承
-
Random
- 屬性
範例
以下範例建立一個單一隨機數產生器,並呼叫其 NextBytes、 Next,以及 NextDouble 產生不同範圍內隨機數序列的方法。
// Instantiate random number generator using system-supplied value as seed.
var rand = new Random();
// Generate and display 5 random byte (integer) values.
byte[] bytes = new byte[5];
rand.NextBytes(bytes);
Console.WriteLine("Five random byte values:");
foreach (byte byteValue in bytes)
Console.Write("{0, 5}", byteValue);
Console.WriteLine();
// Generate and display 5 random integers.
Console.WriteLine("Five random integer values:");
for (int ctr = 0; ctr <= 4; ctr++)
Console.Write("{0,15:N0}", rand.Next());
Console.WriteLine();
// Generate and display 5 random integers between 0 and 100.
Console.WriteLine("Five random integers between 0 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
Console.Write("{0,8:N0}", rand.Next(101));
Console.WriteLine();
// Generate and display 5 random integers from 50 to 100.
Console.WriteLine("Five random integers between 50 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
Console.Write("{0,8:N0}", rand.Next(50, 101));
Console.WriteLine();
// Generate and display 5 random floating point values from 0 to 1.
Console.WriteLine("Five Doubles.");
for (int ctr = 0; ctr <= 4; ctr++)
Console.Write("{0,8:N3}", rand.NextDouble());
Console.WriteLine();
// Generate and display 5 random floating point values from 0 to 5.
Console.WriteLine("Five Doubles between 0 and 5.");
for (int ctr = 0; ctr <= 4; ctr++)
Console.Write("{0,8:N3}", rand.NextDouble() * 5);
// The example displays output like the following:
// Five random byte values:
// 194 185 239 54 116
// Five random integer values:
// 507,353,531 1,509,532,693 2,125,074,958 1,409,512,757 652,767,128
// Five random integers between 0 and 100:
// 16 78 94 79 52
// Five random integers between 50 and 100:
// 56 66 96 60 65
// Five Doubles.
// 0.943 0.108 0.744 0.563 0.415
// Five Doubles between 0 and 5.
// 2.934 3.130 0.292 1.432 4.369
// Instantiate random number generator using system-supplied value as seed.
let rand = Random()
// Generate and display 5 random byte (integer) values.
let bytes = Array.zeroCreate 5
rand.NextBytes bytes
printfn "Five random byte values:"
for byte in bytes do
printf "%5i" byte
printfn ""
// Generate and display 5 random integers.
printfn "Five random integer values:"
for _ = 0 to 4 do
printf $"{rand.Next(),15:N0}"
printfn ""
// Generate and display 5 random integers between 0 and 100.
printfn "Five random integers between 0 and 100:"
for _ = 0 to 4 do
printf $"{rand.Next 101,8:N0}"
printfn ""
// Generate and display 5 random integers from 50 to 100.
printfn "Five random integers between 50 and 100:"
for _ = 0 to 4 do
printf $"{rand.Next(50, 101),8:N0}"
printfn ""
// Generate and display 5 random floating point values from 0 to 1.
printfn "Five Doubles."
for _ = 0 to 4 do
printf $"{rand.NextDouble(),8:N3}"
printfn ""
// Generate and display 5 random floating point values from 0 to 5.
printfn "Five Doubles between 0 and 5."
for _ = 0 to 4 do
printf $"{rand.NextDouble() * 5.0,8:N3}"
// The example displays output like the following:
// Five random byte values:
// 194 185 239 54 116
// Five random integer values:
// 507,353,531 1,509,532,693 2,125,074,958 1,409,512,757 652,767,128
// Five random integers between 0 and 100:
// 16 78 94 79 52
// Five random integers between 50 and 100:
// 56 66 96 60 65
// Five Doubles.
// 0.943 0.108 0.744 0.563 0.415
// Five Doubles between 0 and 5.
// 2.934 3.130 0.292 1.432 4.369
Module Example
Public Sub Main()
' Instantiate random number generator using system-supplied value as seed.
Dim rand As New Random()
' Generate and display 5 random byte (integer) values.
Dim bytes(4) As Byte
rand.NextBytes(bytes)
Console.WriteLine("Five random byte values:")
For Each byteValue As Byte In bytes
Console.Write("{0, 5}", byteValue)
Next
Console.WriteLine()
' Generate and display 5 random integers.
Console.WriteLine("Five random integer values:")
For ctr As Integer = 0 To 4
Console.Write("{0,15:N0}", rand.Next)
Next
Console.WriteLine()
' Generate and display 5 random integers between 0 and 100.'
Console.WriteLine("Five random integers between 0 and 100:")
For ctr As Integer = 0 To 4
Console.Write("{0,8:N0}", rand.Next(101))
Next
Console.WriteLine()
' Generate and display 5 random integers from 50 to 100.
Console.WriteLine("Five random integers between 50 and 100:")
For ctr As Integer = 0 To 4
Console.Write("{0,8:N0}", rand.Next(50, 101))
Next
Console.WriteLine()
' Generate and display 5 random floating point values from 0 to 1.
Console.WriteLine("Five Doubles.")
For ctr As Integer = 0 To 4
Console.Write("{0,8:N3}", rand.NextDouble())
Next
Console.WriteLine()
' Generate and display 5 random floating point values from 0 to 5.
Console.WriteLine("Five Doubles between 0 and 5.")
For ctr As Integer = 0 To 4
Console.Write("{0,8:N3}", rand.NextDouble() * 5)
Next
End Sub
End Module
' The example displays output like the following:
' Five random byte values:
' 194 185 239 54 116
' Five random integer values:
' 507,353,531 1,509,532,693 2,125,074,958 1,409,512,757 652,767,128
' Five random integers between 0 and 100:
' 16 78 94 79 52
' Five random integers between 50 and 100:
' 56 66 96 60 65
' Five Doubles.
' 0.943 0.108 0.744 0.563 0.415
' Five Doubles between 0 and 5.
' 2.934 3.130 0.292 1.432 4.369
以下範例生成一個隨機整數,作為索引,從陣列中檢索字串值。
Random rnd = new();
string[] malePetNames = [ "Rufus", "Bear", "Dakota", "Fido",
"Vanya", "Samuel", "Koani", "Volodya",
"Prince", "Yiska" ];
string[] femalePetNames = [ "Maggie", "Penny", "Saya", "Princess",
"Abby", "Laila", "Sadie", "Olivia",
"Starlight", "Talla" ];
// Generate random indexes for pet names.
int mIndex = rnd.Next(malePetNames.Length);
int fIndex = rnd.Next(femalePetNames.Length);
// Display the result.
Console.WriteLine("Suggested pet name of the day: ");
Console.WriteLine($" For a male: {malePetNames[mIndex]}");
Console.WriteLine($" For a female: {femalePetNames[fIndex]}");
// The example displays output similar to the following:
// Suggested pet name of the day:
// For a male: Koani
// For a female: Maggie
let rnd = Random()
let malePetNames =
[| "Rufus"; "Bear"; "Dakota"; "Fido";
"Vanya"; "Samuel"; "Koani"; "Volodya";
"Prince"; "Yiska" |]
let femalePetNames =
[| "Maggie"; "Penny"; "Saya"; "Princess";
"Abby"; "Laila"; "Sadie"; "Olivia";
"Starlight"; "Talla" |]
// Generate random indexes for pet names.
let mIndex = rnd.Next malePetNames.Length
let fIndex = rnd.Next femalePetNames.Length
// Display the result.
printfn "Suggested pet name of the day: "
printfn " For a male: %s" malePetNames.[mIndex]
printfn " For a female: %s" femalePetNames.[fIndex]
// The example displays output similar to the following:
// Suggested pet name of the day:
// For a male: Koani
// For a female: Maggie
Module Example
Public Sub Main()
Dim rnd As New Random()
Dim malePetNames() As String = { "Rufus", "Bear", "Dakota", "Fido",
"Vanya", "Samuel", "Koani", "Volodya",
"Prince", "Yiska" }
Dim femalePetNames() As String = { "Maggie", "Penny", "Saya", "Princess",
"Abby", "Laila", "Sadie", "Olivia",
"Starlight", "Talla" }
' Generate random indexes for pet names.
Dim mIndex As Integer = rnd.Next(malePetNames.Length)
Dim fIndex As Integer = rnd.Next(femalePetNames.Length)
' Display the result.
Console.WriteLine("Suggested pet name of the day: ")
Console.WriteLine(" For a male: {0}", malePetNames(mIndex))
Console.WriteLine(" For a female: {0}", femalePetNames(fIndex))
End Sub
End Module
' The example displays output similar to the following:
' Suggested pet name of the day:
' For a male: Koani
' For a female: Maggie
備註
備註
若要產生密碼編譯安全隨機數,例如適合建立隨機密碼的隨機數位,請使用 類別中的 RandomNumberGenerator 其中一個靜態方法。
欲了解更多關於此 API 的資訊,請參閱隨機補充 API 備註。
給繼承者的注意事項
在 .NET Framework 2.0 及以後版本中,、Next(Int32, Int32)NextBytes(Byte[])、 和 方法的行為Next()已改變,這些方法不一定會呼叫該方法的Sample()衍生類別實作。 因此,從 Random 該目標 .NET Framework 2.0 及之後版本衍生出的類別也應該覆蓋這三個方法。
給呼叫者的注意事項
類別中 Random 隨機數產生器的實作並不保證在各主要版本的 .NET 中保持一致。 因此,你不應該假設同一個種子在不同版本的 .NET 中會出現相同的偽隨機序列。
建構函式
| 名稱 | Description |
|---|---|
| Random() |
使用預設的種子值初始化該類別的新實例 Random 。 |
| Random(Int32) |
使用指定的種子值初始化該類別的新 Random 實例。 |
屬性
| 名稱 | Description |
|---|---|
| Shared |
提供一個可同時從任何執行緒使用的執行緒安全 Random 實例。 |
方法
| 名稱 | Description |
|---|---|
| Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
| GetHashCode() |
做為預設哈希函式。 (繼承來源 Object) |
| GetHexString(Int32, Boolean) |
建立一個充滿隨機十六進位字元的字串。 |
| GetHexString(Span<Char>, Boolean) |
用隨機的十六進位字元填滿緩衝區。 |
| GetItems<T>(ReadOnlySpan<T>, Int32) |
建立一個陣列,填充從所提供選項中隨機選取的項目。 |
| GetItems<T>(ReadOnlySpan<T>, Span<T>) |
將指定區間的元素填滿從所提供選項集中隨機選擇的項目。 |
| GetItems<T>(T[], Int32) |
建立一個陣列,填充從所提供選項中隨機選取的項目。 |
| GetString(ReadOnlySpan<Char>, Int32) |
建立一個由隨機從中 |
| GetType() |
取得目前實例的 Type。 (繼承來源 Object) |
| MemberwiseClone() |
建立目前 Object的淺層複本。 (繼承來源 Object) |
| Next() |
回傳一個非負的隨機整數。 |
| Next(Int32, Int32) |
回傳一個在指定範圍內的隨機整數。 |
| Next(Int32) |
回傳一個小於指定最大值的非負隨機整數。 |
| NextBytes(Byte[]) |
用隨機數填滿指定位元組陣列的元素。 |
| NextBytes(Span<Byte>) |
用隨機數填補指定位元組區段的元素。 |
| NextDouble() |
回傳一個大於或等於 0.0 且小於 1.0 的隨機浮點數。 |
| NextInt64() |
回傳一個非負的隨機整數。 |
| NextInt64(Int64, Int64) |
回傳一個在指定範圍內的隨機整數。 |
| NextInt64(Int64) |
回傳一個小於指定最大值的非負隨機整數。 |
| NextSingle() |
回傳一個大於或等於 0.0 且小於 1.0 的隨機浮點數。 |
| Sample() |
回傳一個介於 0.0 到 1.0 之間的隨機浮點數。 |
| Shuffle<T>(Span<T>) |
執行原地推移跨距。 |
| Shuffle<T>(T[]) |
執行陣列的原位洗牌。 |
| ToString() |
傳回表示目前 物件的字串。 (繼承來源 Object) |