How do I generate a random int number?

前端 未结 30 2631
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

30条回答
  •  灰色年华
    2020-11-21 11:52

    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.

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

提交回复
热议问题