How do I generate a random int number?

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

How do I generate a random integer in C#?

30条回答
  •  既然无缘
    2020-11-21 12:08

    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

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

提交回复
热议问题