How do I generate a random int number?

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

How do I generate a random integer in C#?

30条回答
  •  难免孤独
    2020-11-21 12:01

    If you want a CSRNG to generate random numbers between a min and max, this is for you. It will initialize Random classes with secure random seeds.

        class SecureRandom : Random
        {
            public static byte[] GetBytes(ulong length)
            {
                RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
                byte[] bytes = new byte[length];
                RNG.GetBytes(bytes);
                RNG.Dispose();
                return bytes;
            }
            public SecureRandom() : base(BitConverter.ToInt32(GetBytes(4), 0))
            {
    
            }
            public int GetRandomInt(int min, int max)
            {
                int treashold = max - min;
                if(treashold != Math.Abs(treashold))
                {
                    throw new ArithmeticException("The minimum value can't exceed the maximum value!");
                }
                if (treashold == 0)
                {
                    throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
                }
                return min + (Next() % treashold);
            }
            public static int GetRandomIntStatic(int min, int max)
            {
                int treashold = max - min;
                if (treashold != Math.Abs(treashold))
                {
                    throw new ArithmeticException("The minimum value can't exceed the maximum value!");
                }
                if(treashold == 0)
                {
                    throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
                }
                return min + (BitConverter.ToInt32(GetBytes(4), 0) % treashold);
            }
        }
    

提交回复
热议问题