C#获取随机数

C#获取随机数最常用的就是直接用new Random().Next(min,max),但这种方法存在一个问题,就是当计算机运算速度足够快的时候,系统来不及计算下一个随机数,最终可能产生一长串相同的数值,也即失去了随机数的意义,下面的算法能比较好的解决这个问题:

        /// <summary>
        /// 获取指定区间的随机数
        /// </summary>
        /// <param name="min">The minimum.</param>
        /// <param name="max">The maximum.</param>
        /// <returns></returns>
        public static int GetRandom(int min=0,int max=30)
        {
            return new Random(GetRandomSeed()).Next(min, max);
        }

        /// <summary>
        /// 加密随机数生成器 生成随机种子
        /// </summary>
        /// <returns></returns>

        static int GetRandomSeed()

        {

            byte[] bytes = new byte[4];

            System.Security.Cryptography.RNGCryptoServiceProvider r= new System.Security.Cryptography.RNGCryptoServiceProvider();

            r.GetBytes(bytes);

            return BitConverter.ToInt32(bytes, 0);

        }

posted @ 2017-07-27 17:01  WCode  阅读(6311)  评论(0编辑  收藏  举报