如何在c#中生成一个随机整数?

时间:2022-12-13 09:07:55

How do I generate a random integer in C#?

如何在c#中生成一个随机整数?

23 个解决方案

#1


1797  

The Random class is used to create random numbers. (Pseudo-random that is of course.).

随机类用于创建随机数。(当然是伪随机事件。)

Example:

例子:

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

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

如果要创建多个随机数,则应该保留随机实例并重用它。如果您在时间上创建了新实例,那么它们将产生与随机生成器从系统时钟中播下的相同序列随机数。

#2


172  

Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

每次执行新的Random()时,它都会被初始化。这意味着在一个紧密的循环中,你会得到相同的值很多次。您应该保留一个随机实例,并在同一实例中继续使用Next。

//Function to get random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
{
    lock(getrandom) // synchronize
    {
        return getrandom.Next(min, max);
    }
}

#3


128  

The question looks very simple but the answer is bit complicated. If you see almost everyone has suggested to use the Random class and some have suggested to use the RNG crypto class. But then when to choose what.

这个问题看起来很简单,但答案有点复杂。如果您看到几乎每个人都建议使用Random类,有些人建议使用RNG加密类。但是什么时候该选择什么。

For that we need to first understand the term RANDOMNESS and the philosophy behind it.

为此,我们需要首先理解随机性和它背后的哲学。

I would encourage you to watch this video which goes in depth in the philosophy of RANDOMNESS using C# https://www.youtube.com/watch?v=tCYxc-2-3fY

我鼓励大家观看这段视频,它深入研究了使用c# https://www.youtube.com/watch?v=tCYxc-2-3fY的《随机性哲学》。

First thing let us understand the philosophy of RANDOMNESS. When we tell a person to choose between RED, GREEN and YELLOW what happens internally. What makes a person choose RED or YELLOW or GREEN?

首先,让我们理解随机性的哲学。当我们告诉一个人在红色、绿色和黄色之间做出选择时,内部发生了什么。是什么让一个人选择红色、黄色或绿色?

如何在c#中生成一个随机整数?

Some initial thought goes into the persons mind which decides his choice, it can be favorite color , lucky color and so on. In other words some initial trigger which we term in RANDOM as SEED.This SEED is the beginning point, the trigger which instigates him to select the RANDOM value.

一些最初的想法进入人的心灵决定他的选择,它可以是最喜欢的颜色,吉祥的颜色等等。换句话说,我们称之为种子的初始触发。这种种子就是起始点,触发他选择随机值的触发点。

Now if a SEED is easy to guess then those kind of random numbers are termed as PSEUDO and when a seed is difficult to guess those random numbers are termed SECURED random numbers.

现在,如果种子很容易猜测,那么这些随机数被称为伪随机数,当种子很难猜测这些随机数被称为安全随机数时。

For example a person chooses is color depending on weather and sound combination then it would be difficult to guess the initial seed.

例如,一个人选择的颜色取决于天气和声音的组合,那么很难猜测最初的种子。

如何在c#中生成一个随机整数?

Now let me make an important statement:-

现在让我做一个重要的声明:-。

*“Random” class generates only PSEUDO random number and to generate SECURE random number we need to use “RNGCryptoServiceProvider” class.

*“随机”类只生成伪随机数,并生成安全随机数,我们需要使用“RNGCryptoServiceProvider”类。

如何在c#中生成一个随机整数?

Random class takes seed values from your CPU clock which is very much predictable. So in other words RANDOM class of C# generates pseudo random numbers , below is the code for the same.

Random类从CPU时钟中获取种子值,这是非常可预测的。换句话说,随机的c#生成伪随机数,下面是相同的代码。

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

While the RNGCryptoServiceProvider class uses OS entropy to generate seeds. OS entropy is a random value which is generated using sound , mouse click and keyboard timings , thermal temp etc. Below goes the code for the same.

而RNGCryptoServiceProvider类使用OS熵来生成种子。OS熵是一个随机的值,它是通过声音、鼠标点击和键盘计时、温度温度等来生成的。

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

To understand OS entropy see this video https://www.youtube.com/watch?v=tCYxc-2-3fY from 11:20 where the logic of OS entropy is explained. So putting in simple words RNG Crypto generates SECURE random numbers.

要理解OS的熵,请查看此视频https://www.youtube.com/watch?从11点20开始解释OS熵的逻辑。因此,用简单的单词RNG加密来生成安全的随机数。

#4


66  

Beware that new Random() is seeded on current timestamp.

请注意,新随机()是在当前时间戳中播种的。

If you want to generate just one number you can use:

如果你想只生成一个数字,你可以使用:

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

新的随机()。Next(int.MinValue int.MaxValue)

For more information, look at the Random class, though please note:

要了解更多信息,请查看Random类,但请注意:

However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers

然而,由于时钟具有有限的分辨率,使用无参数的构造函数来创建不同的随机对象,就会产生随机数生成器,它们产生相同的随机数序列。

So do not use this code to generate a series of random number.

因此,不要使用此代码生成一系列随机数。

#5


42  

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

#6


19  

I wanted to add a cryptographically secure version:

我想添加一个加密安全版本:

RNGCryptoServiceProvider Class (MSDN or dotnetperls)

RNGCryptoServiceProvider类(MSDN或dotnetperls)

It implements IDisposable.

它实现IDisposable。

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

#7


14  

it's better to seed the Random object with current milliseconds, to ensure true random number, and you almost won't find duplicates using it many times

最好是用当前的毫秒来播种随机的对象,以确保真正的随机数,并且你几乎不会发现重复使用它多次。

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

#8


12  

You could use Jon Skeet's StaticRandom method inside the MiscUtil class library that he built for a pseudo-random number.

您可以使用Jon Skeet的StaticRandom方法在他为一个伪随机数构建的MiscUtil类库中。

using System;
using MiscUtil;

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

#9


10  

I've tried all of these solutions excluding the COBOL answer... lol

我已经尝试了所有这些解决方案,不包括COBOL答案……哈哈

None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

这些解决方案都不够好。我需要一个快速的for int循环,即使在非常大的范围内,我也得到了大量重复的值。在确定了一些随机的结果之后,我决定最终彻底解决这个问题。

It's all about the seed.

都是关于种子的。

I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

我通过解析Guid上的非数字创建一个随机整数,然后用它实例化我的随机类。

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);
}

Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

更新:如果您一次实例化Random类,则不需要播种。所以最好创建一个静态类,然后调用一个方法。

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);
   }
}

Then you can use the static class like so..

然后就可以使用静态类了。

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

I admit I like this approach better.

我承认我更喜欢这种方法。

#10


6  

I use below code to have a random number:

我用下面的代码有一个随机数:

var random = new Random((int)DateTime.Now.Ticks);
var randomValue = random.Next(startValue, endValue + 1);

#11


5  

The numbers generated by the inbuilt Random class (System.Random) generates pseudo random numbers.

由内置随机类(System.Random)生成的数字生成伪随机数。

If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider.

如果您想要真正的随机数,我们可以得到的最接近的是“安全伪随机生成器”,它可以通过使用c#(比如RNGCryptoServiceProvider)中的加密类生成。

Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.

即使如此,如果你仍然需要真实的随机数,你就需要使用外部源,比如设备,作为随机数生成器的种子。因为,根据定义,任何由纯算法产生的数字都不能是真正随机的。

#12


3  

Modified answer from here.

从这里修改答案。

If you have access to an Intel Secure Key compatible CPU, you can generate real random numbers and strings using these libraries: https://github.com/JebteK/RdRand and https://www.rdrand.com/

如果您有访问Intel安全密钥兼容的CPU,您可以使用这些库生成真正的随机数和字符串:https://github.com/JebteK/RdRand和https://www.rdrand.com/。

Just download the latest version from here, include Jebtek.RdRand and add a using statement for it. Then, all you need to do is this:

从这里下载最新版本,包括Jebtek。RdRand为其添加一个using语句。然后,你需要做的就是:

bool isAvailable = RdRandom.GeneratorAvailable(); //Check to see if this is a compatible CPU
string key = RdRandom.GenerateKey(10); //Generate 10 random characters
string apiKey = RdRandom.GenerateAPIKey(); //Generate 64 random characters, useful for API keys
byte[] b = RdRandom.GenerateBytes(10); //Generate an array of 10 random bytes
uint i = RdRandom.GenerateUnsignedInt() //Generate a random unsigned int

If you don't have a compatible CPU to execute the code on, just use the RESTful services at rdrand.com. With the RdRandom wrapper library included in your project, you would just need to do this (you get 1000 free calls when you signup):

如果您没有一个兼容的CPU来执行代码,只需在rdrand.com上使用RESTful服务。在您的项目中包含了RdRandom包装库,您只需要这样做(注册时可以获得1000个免费调用):

string ret = Randomizer.GenerateKey(<length>, "<key>");
uint ret = Randomizer.GenerateUInt("<key>");
byte[] ret = Randomizer.GenerateBytes(<length>, "<key>");

#13


3  

While this is okay:

虽然这是好的:

Random random = new Random();
int randomNumber = random.Next()

You'd want to control the limit (min and max mumbers) most of the time. So you need to specify where the random number starts and ends.

大多数时候,你都想控制极限(最小值和最大值)。所以你需要指定随机数开始和结束的位置。

The Next() method accepts two parameters, min and max.

下一个()方法接受两个参数min和max。

So if i want my random number to be between say 5 and 15, I'd just do

所以如果我想让随机数介于5和15之间,我就这么做。

int randomNumber = random.Next(5, 16)

#14


3  

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

#15


3  

This is the class I use. Works like RandomNumber.GenerateRandom(1, 666)

这是我使用的类。像RandomNumber工作。GenerateRandom(666)

internal static class RandomNumber
{
    private static Random r = new Random();
    private static object l = new object();
    private static Random globalRandom = new Random();
    [ThreadStatic]
    private static Random localRandom;
    public static int GenerateNewRandom(int min, int max)
    {
        return new Random().Next(min, max);
    }
    public static int GenerateLockedRandom(int min, int max)
    {
        int result;
        lock (RandomNumber.l)
        {
            result = RandomNumber.r.Next(min, max);
        }
        return result;
    }
    public static int GenerateRandom(int min, int max)
    {
        Random random = RandomNumber.localRandom;
        if (random == null)
        {
            int seed;
            lock (RandomNumber.globalRandom)
            {
                seed = RandomNumber.globalRandom.Next();
            }
            random = (RandomNumber.localRandom = new Random(seed));
        }
        return random.Next(min, max);
    }
}

#16


2  

Random rand = new Random();
int name = rand.Next()

Put whatever values you want in the second parentheses make sure you have set a name by writing prop and double tab to generate the code

在第二个括号中放入您想要的值,确保您已经通过写入prop和double选项卡设置了一个名称来生成代码。

#17


1  

Numbers calculated by a computer through a deterministic process, cannot, by definition, be random.

由计算机通过确定性过程计算的数字,根据定义,不能是随机的。

If you want a genuine random numbers, the randomness comes from atmospheric noise or radioactive decay.

如果你想要一个真正的随机数,随机性来自于大气噪声或放射性衰变。

You can try for example RANDOM.ORG (it reduces performance)

你可以尝试随机选择。ORG(减少性能)

#18


1  

I wanted to demonstrate what happens when a new random generator is used every time. Suppose you have two methods or two classes each requiring a random number. And naively you code them like:

我想演示当每次使用一个新的随机生成器时会发生什么。假设您有两个方法或两个类,每个都需要一个随机数。很天真地把它们编码成:

public class A
{
    public A()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}

Do you think you will get two different IDs? NOPE

你会得到两个不同的id吗?不

class Program
{
    static void Main(string[] args)
    {
        A a=new A();
        B b=new B();

        int ida=a.ID, idb=b.ID;
        // ida = 1452879101
        // idb = 1452879101
    }
}

The solution is to always use a single static random generator. Like this:

解决方案是始终使用单个静态随机生成器。是这样的:

public static class Utils
{
    public static readonly Random random=new Random();
}

public class A
{
    public A()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}

#19


0  

Why not use int randomNumber = Random.Range(start_range, end_range) ?

为什么不使用int随机数= Random。范围(start_range,end_range)?

#20


0  

Try these simple steps to create random numbers:

试试下面这些简单的步骤来创建随机数:

create function

创建函数

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

Use the above function in a location where you want to use random numbers. Suppose you want to use it in a text box.

在你想要使用随机数的地方使用上面的函数。假设您想在文本框中使用它。

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

0 is min and 999 is max. You can change the values to whatever you want.

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

Also check the answer on this page.

还可以在这个页面上查看答案。

(http://solutions.musanitech.com/c-how-to-create-random-numbers/)

(http://solutions.musanitech.com/c-how-to-create-random-numbers/)

#21


0  

You can try with random seed value using below:

你可以尝试使用下面的随机种子值:

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

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

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

#22


0  

Quick and easy for inline, use bellow code:

快速且易于内联,使用bellow代码:

new Random().Next(min, max);

// for example unique name
strName += "_" + new Random().Next(100, 999);

#23


-1  

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

you can also give minimum and maximum value to Next() function. Like

您还可以为Next()函数提供最小值和最大值。就像

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

#1


1797  

The Random class is used to create random numbers. (Pseudo-random that is of course.).

随机类用于创建随机数。(当然是伪随机事件。)

Example:

例子:

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

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

如果要创建多个随机数,则应该保留随机实例并重用它。如果您在时间上创建了新实例,那么它们将产生与随机生成器从系统时钟中播下的相同序列随机数。

#2


172  

Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

每次执行新的Random()时,它都会被初始化。这意味着在一个紧密的循环中,你会得到相同的值很多次。您应该保留一个随机实例,并在同一实例中继续使用Next。

//Function to get random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
{
    lock(getrandom) // synchronize
    {
        return getrandom.Next(min, max);
    }
}

#3


128  

The question looks very simple but the answer is bit complicated. If you see almost everyone has suggested to use the Random class and some have suggested to use the RNG crypto class. But then when to choose what.

这个问题看起来很简单,但答案有点复杂。如果您看到几乎每个人都建议使用Random类,有些人建议使用RNG加密类。但是什么时候该选择什么。

For that we need to first understand the term RANDOMNESS and the philosophy behind it.

为此,我们需要首先理解随机性和它背后的哲学。

I would encourage you to watch this video which goes in depth in the philosophy of RANDOMNESS using C# https://www.youtube.com/watch?v=tCYxc-2-3fY

我鼓励大家观看这段视频,它深入研究了使用c# https://www.youtube.com/watch?v=tCYxc-2-3fY的《随机性哲学》。

First thing let us understand the philosophy of RANDOMNESS. When we tell a person to choose between RED, GREEN and YELLOW what happens internally. What makes a person choose RED or YELLOW or GREEN?

首先,让我们理解随机性的哲学。当我们告诉一个人在红色、绿色和黄色之间做出选择时,内部发生了什么。是什么让一个人选择红色、黄色或绿色?

如何在c#中生成一个随机整数?

Some initial thought goes into the persons mind which decides his choice, it can be favorite color , lucky color and so on. In other words some initial trigger which we term in RANDOM as SEED.This SEED is the beginning point, the trigger which instigates him to select the RANDOM value.

一些最初的想法进入人的心灵决定他的选择,它可以是最喜欢的颜色,吉祥的颜色等等。换句话说,我们称之为种子的初始触发。这种种子就是起始点,触发他选择随机值的触发点。

Now if a SEED is easy to guess then those kind of random numbers are termed as PSEUDO and when a seed is difficult to guess those random numbers are termed SECURED random numbers.

现在,如果种子很容易猜测,那么这些随机数被称为伪随机数,当种子很难猜测这些随机数被称为安全随机数时。

For example a person chooses is color depending on weather and sound combination then it would be difficult to guess the initial seed.

例如,一个人选择的颜色取决于天气和声音的组合,那么很难猜测最初的种子。

如何在c#中生成一个随机整数?

Now let me make an important statement:-

现在让我做一个重要的声明:-。

*“Random” class generates only PSEUDO random number and to generate SECURE random number we need to use “RNGCryptoServiceProvider” class.

*“随机”类只生成伪随机数,并生成安全随机数,我们需要使用“RNGCryptoServiceProvider”类。

如何在c#中生成一个随机整数?

Random class takes seed values from your CPU clock which is very much predictable. So in other words RANDOM class of C# generates pseudo random numbers , below is the code for the same.

Random类从CPU时钟中获取种子值,这是非常可预测的。换句话说,随机的c#生成伪随机数,下面是相同的代码。

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

While the RNGCryptoServiceProvider class uses OS entropy to generate seeds. OS entropy is a random value which is generated using sound , mouse click and keyboard timings , thermal temp etc. Below goes the code for the same.

而RNGCryptoServiceProvider类使用OS熵来生成种子。OS熵是一个随机的值,它是通过声音、鼠标点击和键盘计时、温度温度等来生成的。

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

To understand OS entropy see this video https://www.youtube.com/watch?v=tCYxc-2-3fY from 11:20 where the logic of OS entropy is explained. So putting in simple words RNG Crypto generates SECURE random numbers.

要理解OS的熵,请查看此视频https://www.youtube.com/watch?从11点20开始解释OS熵的逻辑。因此,用简单的单词RNG加密来生成安全的随机数。

#4


66  

Beware that new Random() is seeded on current timestamp.

请注意,新随机()是在当前时间戳中播种的。

If you want to generate just one number you can use:

如果你想只生成一个数字,你可以使用:

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

新的随机()。Next(int.MinValue int.MaxValue)

For more information, look at the Random class, though please note:

要了解更多信息,请查看Random类,但请注意:

However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers

然而,由于时钟具有有限的分辨率,使用无参数的构造函数来创建不同的随机对象,就会产生随机数生成器,它们产生相同的随机数序列。

So do not use this code to generate a series of random number.

因此,不要使用此代码生成一系列随机数。

#5


42  

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

#6


19  

I wanted to add a cryptographically secure version:

我想添加一个加密安全版本:

RNGCryptoServiceProvider Class (MSDN or dotnetperls)

RNGCryptoServiceProvider类(MSDN或dotnetperls)

It implements IDisposable.

它实现IDisposable。

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

#7


14  

it's better to seed the Random object with current milliseconds, to ensure true random number, and you almost won't find duplicates using it many times

最好是用当前的毫秒来播种随机的对象,以确保真正的随机数,并且你几乎不会发现重复使用它多次。

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

#8


12  

You could use Jon Skeet's StaticRandom method inside the MiscUtil class library that he built for a pseudo-random number.

您可以使用Jon Skeet的StaticRandom方法在他为一个伪随机数构建的MiscUtil类库中。

using System;
using MiscUtil;

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

#9


10  

I've tried all of these solutions excluding the COBOL answer... lol

我已经尝试了所有这些解决方案,不包括COBOL答案……哈哈

None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

这些解决方案都不够好。我需要一个快速的for int循环,即使在非常大的范围内,我也得到了大量重复的值。在确定了一些随机的结果之后,我决定最终彻底解决这个问题。

It's all about the seed.

都是关于种子的。

I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

我通过解析Guid上的非数字创建一个随机整数,然后用它实例化我的随机类。

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);
}

Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

更新:如果您一次实例化Random类,则不需要播种。所以最好创建一个静态类,然后调用一个方法。

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);
   }
}

Then you can use the static class like so..

然后就可以使用静态类了。

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

I admit I like this approach better.

我承认我更喜欢这种方法。

#10


6  

I use below code to have a random number:

我用下面的代码有一个随机数:

var random = new Random((int)DateTime.Now.Ticks);
var randomValue = random.Next(startValue, endValue + 1);

#11


5  

The numbers generated by the inbuilt Random class (System.Random) generates pseudo random numbers.

由内置随机类(System.Random)生成的数字生成伪随机数。

If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider.

如果您想要真正的随机数,我们可以得到的最接近的是“安全伪随机生成器”,它可以通过使用c#(比如RNGCryptoServiceProvider)中的加密类生成。

Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.

即使如此,如果你仍然需要真实的随机数,你就需要使用外部源,比如设备,作为随机数生成器的种子。因为,根据定义,任何由纯算法产生的数字都不能是真正随机的。

#12


3  

Modified answer from here.

从这里修改答案。

If you have access to an Intel Secure Key compatible CPU, you can generate real random numbers and strings using these libraries: https://github.com/JebteK/RdRand and https://www.rdrand.com/

如果您有访问Intel安全密钥兼容的CPU,您可以使用这些库生成真正的随机数和字符串:https://github.com/JebteK/RdRand和https://www.rdrand.com/。

Just download the latest version from here, include Jebtek.RdRand and add a using statement for it. Then, all you need to do is this:

从这里下载最新版本,包括Jebtek。RdRand为其添加一个using语句。然后,你需要做的就是:

bool isAvailable = RdRandom.GeneratorAvailable(); //Check to see if this is a compatible CPU
string key = RdRandom.GenerateKey(10); //Generate 10 random characters
string apiKey = RdRandom.GenerateAPIKey(); //Generate 64 random characters, useful for API keys
byte[] b = RdRandom.GenerateBytes(10); //Generate an array of 10 random bytes
uint i = RdRandom.GenerateUnsignedInt() //Generate a random unsigned int

If you don't have a compatible CPU to execute the code on, just use the RESTful services at rdrand.com. With the RdRandom wrapper library included in your project, you would just need to do this (you get 1000 free calls when you signup):

如果您没有一个兼容的CPU来执行代码,只需在rdrand.com上使用RESTful服务。在您的项目中包含了RdRandom包装库,您只需要这样做(注册时可以获得1000个免费调用):

string ret = Randomizer.GenerateKey(<length>, "<key>");
uint ret = Randomizer.GenerateUInt("<key>");
byte[] ret = Randomizer.GenerateBytes(<length>, "<key>");

#13


3  

While this is okay:

虽然这是好的:

Random random = new Random();
int randomNumber = random.Next()

You'd want to control the limit (min and max mumbers) most of the time. So you need to specify where the random number starts and ends.

大多数时候,你都想控制极限(最小值和最大值)。所以你需要指定随机数开始和结束的位置。

The Next() method accepts two parameters, min and max.

下一个()方法接受两个参数min和max。

So if i want my random number to be between say 5 and 15, I'd just do

所以如果我想让随机数介于5和15之间,我就这么做。

int randomNumber = random.Next(5, 16)

#14


3  

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

#15


3  

This is the class I use. Works like RandomNumber.GenerateRandom(1, 666)

这是我使用的类。像RandomNumber工作。GenerateRandom(666)

internal static class RandomNumber
{
    private static Random r = new Random();
    private static object l = new object();
    private static Random globalRandom = new Random();
    [ThreadStatic]
    private static Random localRandom;
    public static int GenerateNewRandom(int min, int max)
    {
        return new Random().Next(min, max);
    }
    public static int GenerateLockedRandom(int min, int max)
    {
        int result;
        lock (RandomNumber.l)
        {
            result = RandomNumber.r.Next(min, max);
        }
        return result;
    }
    public static int GenerateRandom(int min, int max)
    {
        Random random = RandomNumber.localRandom;
        if (random == null)
        {
            int seed;
            lock (RandomNumber.globalRandom)
            {
                seed = RandomNumber.globalRandom.Next();
            }
            random = (RandomNumber.localRandom = new Random(seed));
        }
        return random.Next(min, max);
    }
}

#16


2  

Random rand = new Random();
int name = rand.Next()

Put whatever values you want in the second parentheses make sure you have set a name by writing prop and double tab to generate the code

在第二个括号中放入您想要的值,确保您已经通过写入prop和double选项卡设置了一个名称来生成代码。

#17


1  

Numbers calculated by a computer through a deterministic process, cannot, by definition, be random.

由计算机通过确定性过程计算的数字,根据定义,不能是随机的。

If you want a genuine random numbers, the randomness comes from atmospheric noise or radioactive decay.

如果你想要一个真正的随机数,随机性来自于大气噪声或放射性衰变。

You can try for example RANDOM.ORG (it reduces performance)

你可以尝试随机选择。ORG(减少性能)

#18


1  

I wanted to demonstrate what happens when a new random generator is used every time. Suppose you have two methods or two classes each requiring a random number. And naively you code them like:

我想演示当每次使用一个新的随机生成器时会发生什么。假设您有两个方法或两个类,每个都需要一个随机数。很天真地把它们编码成:

public class A
{
    public A()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}

Do you think you will get two different IDs? NOPE

你会得到两个不同的id吗?不

class Program
{
    static void Main(string[] args)
    {
        A a=new A();
        B b=new B();

        int ida=a.ID, idb=b.ID;
        // ida = 1452879101
        // idb = 1452879101
    }
}

The solution is to always use a single static random generator. Like this:

解决方案是始终使用单个静态随机生成器。是这样的:

public static class Utils
{
    public static readonly Random random=new Random();
}

public class A
{
    public A()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}

#19


0  

Why not use int randomNumber = Random.Range(start_range, end_range) ?

为什么不使用int随机数= Random。范围(start_range,end_range)?

#20


0  

Try these simple steps to create random numbers:

试试下面这些简单的步骤来创建随机数:

create function

创建函数

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

Use the above function in a location where you want to use random numbers. Suppose you want to use it in a text box.

在你想要使用随机数的地方使用上面的函数。假设您想在文本框中使用它。

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

0 is min and 999 is max. You can change the values to whatever you want.

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

Also check the answer on this page.

还可以在这个页面上查看答案。

(http://solutions.musanitech.com/c-how-to-create-random-numbers/)

(http://solutions.musanitech.com/c-how-to-create-random-numbers/)

#21


0  

You can try with random seed value using below:

你可以尝试使用下面的随机种子值:

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

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

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

#22


0  

Quick and easy for inline, use bellow code:

快速且易于内联,使用bellow代码:

new Random().Next(min, max);

// for example unique name
strName += "_" + new Random().Next(100, 999);

#23


-1  

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

you can also give minimum and maximum value to Next() function. Like

您还可以为Next()函数提供最小值和最大值。就像

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