按一下以給予評分及指教
MSDN
MSDN Library
.NET 開發
.NET Framework
Random 類別

  開啟低頻寬檢視
本頁僅適用於
Microsoft Visual Studio 2008/.NET Framework 3.5

其他版本也適用於下列軟體:
.NET Framework 類別庫
Random 類別

更新:2007 年 11 月

表示虛擬亂數產生器,為產生數字序列 (Sequence) 的裝置,符合隨機方式的特定統計需求。

命名空間:  System
組件:  mscorlib (在 mscorlib.dll 中)
Visual Basic (宣告)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class Random
Visual Basic (使用方式)
Dim instance As Random
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class Random
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class Random
J#
/** @attribute SerializableAttribute */ 
/** @attribute ComVisibleAttribute(true) */
public class Random
JScript
public class Random

虛擬亂數是以相等的機率從有限的數字集中選取。選取的數字並非是完全隨機,因為是使用有限性數學演算法來選取它們,但是用於實際用途已足夠。目前 Random 類別的實作是以 Donald E. Knuth 的減法亂數產生器演算法為基準。如需詳細資訊,請參閱 D. E. Knuth 所著的《The Art of Computer Programming, volume 2: Seminumerical Algorithms》,Addison-Wesley, Reading, MA, second edition, 1981。

亂數的產生始於種子值。如果重複使用相同的種子會產生相同的連續數字。其中一個產生不同序列的方法是讓種子值時間相依,由此以每個 Random 的新執行個體 (Instance) 產生不同的系列。根據預設,Random 類別的無參數建構函式會使用系統時鐘來產生其種子值,而參數化的建構函式可以根據目前時間的刻度數目而接受 Int32 值。然而,因為時鐘的解析度有限,所以若使用無參數的建構函式在極短時間內連續建立不同的 Random 物件,就會建立亂數產生器,這些產生器會產生序列完全相同的亂數。下列範例說明短時間內連續產生一系列相同亂數的兩個 Random 物件。

Visual Basic
Dim bytes1(99), bytes2(99) As Byte
Dim rnd1 As New Random()
Dim rnd2 As New Random()

rnd1.NextBytes(bytes1)
rnd2.NextBytes(bytes2)

Console.WriteLine("First Series:")
For ctr As Integer = bytes1.GetLowerBound(0) to bytes1.GetUpperBound(0)
   Console.Write("{0, 5}", bytes1(ctr))
   If (ctr + 1) Mod 10 = 0 Then Console.WriteLine()
Next 
Console.WriteLine()
Console.WriteLine("Second Series:")        
For ctr As Integer = bytes2.GetLowerBound(0) to bytes2.GetUpperBound(0)
   Console.Write("{0, 5}", bytes2(ctr))
   If (ctr + 1) Mod 10 = 0 Then Console.WriteLine()
Next   
' The example displays the following output to the console:
'       First Series:
'          97  129  149   54   22  208  120  105   68  177
'         113  214   30  172   74  218  116  230   89   18
'          12  112  130  105  116  180  190  200  187  120
'           7  198  233  158   58   51   50  170   98   23
'          21    1  113   74  146  245   34  255   96   24
'         232  255   23    9  167  240  255   44  194   98
'          18  175  173  204  169  171  236  127  114   23
'         167  202  132   65  253   11  254   56  214  127
'         145  191  104  163  143    7  174  224  247   73
'          52    6  231  255    5  101   83  165  160  231
'       
'       Second Series:
'          97  129  149   54   22  208  120  105   68  177
'         113  214   30  172   74  218  116  230   89   18
'          12  112  130  105  116  180  190  200  187  120
'           7  198  233  158   58   51   50  170   98   23
'          21    1  113   74  146  245   34  255   96   24
'         232  255   23    9  167  240  255   44  194   98
'          18  175  173  204  169  171  236  127  114   23
'         167  202  132   65  253   11  254   56  214  127
'         145  191  104  163  143    7  174  224  247   73
'          52    6  231  255    5  101   83  165  160  231      

C#
byte[] bytes1 = new byte[100];
byte[] bytes2 = new byte[100];
Random rnd1 = new Random();
Random rnd2 = new Random();

rnd1.NextBytes(bytes1);
rnd2.NextBytes(bytes2);

Console.WriteLine("First Series:");
for (int ctr = bytes1.GetLowerBound(0); 
     ctr <= bytes1.GetUpperBound(0); 
     ctr++) { 
   Console.Write("{0, 5}", bytes1[ctr]);
   if ((ctr + 1) % 10 == 0) Console.WriteLine();
} 
Console.WriteLine();
Console.WriteLine("Second Series:");        
for (int ctr = bytes2.GetLowerBound(0);
     ctr <= bytes2.GetUpperBound(0);
     ctr++) {
   Console.Write("{0, 5}", bytes2[ctr]);
   if ((ctr + 1) % 10 == 0) Console.WriteLine();
}   
// The example displays the following output to the console:
//       First Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231
//       
//       Second Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231        

只要建立單一 Random 物件,而不要建立多個物件,就可以避免這個問題。

為了改善效能,請建立一個 Random 物件,以便在一段時間內產生許多亂數,而不要重複地建立新的 Random 物件來產生一個亂數。

例如,若要產生密碼學上適用於建立隨機密碼的安全亂數,則使用從 System.Security.Cryptography..::.RandomNumberGenerator 衍生的類別,例如 System.Security.Cryptography..::.RNGCryptoServiceProvider

繼承者注意事項

在 .NET Framework 1.0 和 1.1 版中,衍生自 Random 的類別最小實作 (Implementation) 需要覆寫 Sample 方法,用以定義產生亂數的全新或修改過的演算法。衍生類別 (Derived Class) 接著會依賴 Random..::.Next()()()Random..::.Next(Int32)Random..::.Next(Int32, Int32)NextBytesNextDouble 方法的基底類別 (Base Class) 實作,呼叫 Sample 方法的衍生類別實作。

在 .NET Framework 2.0 (含) 以後版本中,Random..::.Next()()()Random..::.Next(Int32, Int32)NextBytes 方法的行為已經變更,因此這些方法並不需要呼叫 Sample 方法的衍生類別實作。因此,衍生自使用 .NET Framework 2.0 (含) 以後版本之 Random 的類別應該也會覆寫這三種方法。

下列範例會建立單一亂數產生器,並且呼叫其 NextBytesNextNextDouble 方法,產生不同範圍的亂數序列。

Visual Basic
' 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                     
' Sample console output might appear as follows:
'    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      

C#
// Instantiate random number generator using system-supplied value as seed.
Random rand = new Random();
// Generate and display 5 random byte (integer) values.
byte[] bytes = new byte[4];
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);
// Sample console output might appear as follows:
//    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      

System..::.Object
  System..::.Random
這個型別的任何 Public static (在 Visual Basic 中為 Shared) 成員都具備執行緒安全。並非所有的執行個體成員都是安全執行緒。

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

.NET Framework 和 .NET Compact Framework 並不支援各種平台的所有版本。如需支援平台版本的相關資訊,請參閱 .NET Framework 系統需求

.NET Framework

支援版本:3.5、3.0、2.0、1.1、1.0

.NET Compact Framework

支援版本:3.5、2.0、1.0

XNA Framework

支援版本:2.0、1.0
社群內容   什麼是社群內容?
新增內容 RSS  註解
Processing
© 2009 Microsoft Corporation. 著作權所有,並保留一切權利。 使用規定  |  商標  |  隱私權聲明
Page view tracker