سلام دوست عزیز،
برای تولید اعداد تصادفی با استفاده از کلاس Random نیازی به نمونه سازی مجدد برای تولید هر عدد نیست، به نقل از MSDN:
The default seed value is derived from the
system clock and has finite resolution. As a result, different
Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of
random numbers. This problem can be avoided by using a single
Random object to generate all
random numbers.
پس، از یک شیء کلاس Random برای تولید اعداد تصادفی استفاده کرده یا اینکه برای هر شیء مقدار seed متفاوتی را قرار دهید،
در ضمن، راه حل اصولی و مطمئن برای تولید اعداد تصادفی بهره گیری از کلاس System.Security.Cryptography.RNGCryptoServiceProvi der می باشد،
مثالی از MSDN:
//The following sample uses the Cryptography class to simulate the roll of a dice.
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
class RNGCSP
{
// Main method.
public static void Main()
{
// Roll the dice 30 times and display
// the results to the console.
for(int x = 0; x < 30; x++)
Console.WriteLine(RollDice(6));
}
// This method simulates a roll of the dice. The input parameter is the
// number of sides of the dice.
public static int RollDice(int NumSides)
{
// Create a byte array to hold the random value.
byte[] randomNumber = new byte[1];
// Create a new instance of the RNGCryptoServiceProvider.
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
// Fill the array with a random value.
Gen.GetBytes(randomNumber);
// Convert the byte to an integer value to make the modulus operation easier.
int rand = Convert.ToInt32(randomNumber[0]);
// Return the random number mod the number
// of sides. The possible values are zero-
// based, so we add one.
return rand % NumSides + 1;
}
}
،/