【C#】Random生成随机数重复的问题

发布时间 2023-04-18 11:19:17作者: 不溯流光
    /// <summary>
    /// 根据中位数返回区间随机数
    /// </summary>
    /// <param name="mid"></param>
    /// <returns></returns>
    private static int GetRandom(int mid)
    {
        //1.
        //Random ran = new Random();

        //2.
        //Random ran = new Random(new Guid().GetHashCode());

        //3.
        //long tick = DateTime.Now.Ticks;
        //Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));

        //4.(*有效方法)
        //Thread.Sleep(100);
        //Random ran = new Random();

        //5.(*有效方法)
        Random ran = new Random(GetRandomSeed());

        return ran.Next(mid -5,mid +10);
    }

    static int GetRandomSeed()
    {
        byte[] bytes = new byte[4];
        System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
        rng.GetBytes(bytes);
        return BitConverter.ToInt32(bytes, 0);
    }


//控制台打印,测试一下
 static void Main(string[] args)
 {

      int count = 0;
     Random ran = new Random();
     int mid = 33;
     while (count < 50)
     {
         Console.WriteLine(GetRandom(mid));
         count++;
     }
     Console.ReadKey();
 }

 

来源:https://blog.csdn.net/shuai_wy/article/details/78606175