如何在一段时间内生成相同的伪随机数?比如现在是2011年5月8号20点29分,按照算法生成一个伪随机数,那么在未来的一段时间假如10分钟之内,都会生成上面相同的伪随机数。请问高手如何实现??多谢

解决方案 »

  1.   

    写个类将Random和DateTime包装一下就行了        public class RandomValueGenerater
            {
                public DateTime LastTime { set; get; }
                public TimeSpan SameTime { set; get; }
                public int LastRandomValue { set; get; }            private Random _random;            public RandomValueGenerater(TimeSpan span)
                {
                    SameTime = span;
                    _random = new Random((int)DateTime.Now.Ticks);
                }            public int GetNext()
                {
                    if (DateTime.Now - LastTime > SameTime)
                    {
                        LastTime = DateTime.Now;
                        LastRandomValue = _random.Next();
                    }
                    return LastRandomValue;
                }
            }        static void Main(string[] args)
            {
                RandomValueGenerater r = new RandomValueGenerater(new TimeSpan(0, 0, 5));
                while (true)
                {
                    Console.WriteLine(r.GetNext());
                    Thread.Sleep(1000);
                }
            }
      

  2.   


        class Program
        {
            static void Main(string[] args)
            {
                System.Timers.Timer timer = new System.Timers.Timer(5000);
                timer.Elapsed += (sender, e) =>
                {
                    Program p = new Program();
                    Console.WriteLine(p.GetRandomNumber());
                };
                timer.Start();
                Console.Read();
            }        static DateTime dt = DateTime.Now;        static int random;        Random r = new Random();        public int GetRandomNumber()
            {
                TimeSpan ts = DateTime.Now - dt;
                if (ts.TotalSeconds >= 20 || random == 0)//这里把ts.TotalSeconds换成ts.TotalMinutes就是分钟了
                {
                    dt = DateTime.Now;
                    random = r.Next(0, (int)(dt - new DateTime(dt.Year, 1, 1)).TotalMinutes);
                }
                return random;
            }
        }