# c# - 随机整数 - unity随机数

## 如何在C#中生成一个随机int数? (15)

`Random`用于创建随机数。 （当然是伪随机）。

``````Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7);   // creates a number between 1 and 6
int card = rnd.Next(52);     // creates a number between 0 and 51
``````

``````var rnd = new Random(11111111); //note: seed value is 11111111

string randomDigits = rnd.Next().ToString().Substring(0, 8);

var requestNumber = \$"SD-{randomDigits}";
``````

``````using System;
using MiscUtil;

class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(StaticRandom.Next());
}
}
}
``````

``````public int GenerateRandom(int min, int max)
{
var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
return new Random(seed).Next(min, max);
}
``````

``````public static class IntUtil
{
private static Random random;

private static void Init()
{
if (random == null) random = new Random();
}

public static int Random(int min, int max)
{
Init();
return random.Next(min, max);
}
}
``````

``````for(var i = 0; i < 1000; i++)
{
int randomNumber = IntUtil.Random(1,100);
Console.WriteLine(randomNumber);
}
``````

RNGCryptoServiceProvider类（ MSDNdotnetperls

``````using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] randomNumber = new byte[4];//4 for int32
rng.GetBytes(randomNumber);
int value = BitConverter.ToInt32(randomNumber, 0);
}
``````

``````Random rand = new Random(DateTime.Now.Millisecond);
``````

`new Random().Next( int.MinValue, int.MaxValue )`

``````private int randomnumber(int min, int max)
{
Random rnum = new Random();
return rnum.Next(min, max);
}
``````

``````textBox1.Text = randomnumber(0, 999).ToString();
``````

0分最小，999最大。 您可以将值更改为任何您想要的值。

*“随机”类仅生成PSEUDO随机数并生成SECURE随机数，我们需要使用“RNGCryptoServiceProvider”类。

``````Random rnd= new Random();
int rndnumber = rnd.Next()
``````

RNGCryptoServiceProvider类使用OS熵来生成种子。 OS熵是一个随机值，它是使用声音，鼠标点击和键盘计时，热温度等产生的。以下代码为相同。

``````using (RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider())
{
byte[] rno = new byte[5];
rg.GetBytes(rno);
int randomvalue = BitConverter.ToInt32(rno, 0);
}
``````

`````` int n = new Random().Next();
``````

`````` int n = new Random().Next(5,10);
``````

``````Random r = new Random();
int n = r.Next();
``````

``````Random randomNumberGenerator = new Random ();
int randomNumber = randomNumberGenerator.Next (lowerBound,upperBound);
``````