范围内的随机ThreadStatic数

时间:2015-04-04 14:30:30

标签: c# asp.net random rngcryptoserviceprovider

如何使用线性种子从一系列数字中生成随机数?

我需要在多个方法的范围内创建随机数。问题是旧的重复问题。

我发现一个MSDN博客有一个很好的随机生成器,但我需要两个值之间的范围(通常为0 - 100)。

  

http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx

public static class RandomGenNumber
    {
        private static RNGCryptoServiceProvider _global =
            new RNGCryptoServiceProvider();
        [ThreadStatic]
        private static Random _local;

        //this works
        public static int Next()
        {
            Random inst = _local;
            if (inst == null)
            {
                byte[] buffer = new byte[4];
                _global.GetBytes(buffer);
                _local = inst = new Random(
                    BitConverter.ToInt32(buffer, 0));
            }
            return inst.Next();
        }

        //this is what needs to be fixed
        public static int Next(int low, int high)
        {
            Random inst = _local;
            if (inst == null)
            {
                byte[] buffer = ????;

                _global.GetBytes(buffer);
                _local = inst = new Random(
                    BitConverter.ToInt32(buffer, 0));
            }
            return inst.Next();
        }
    } 

当我循环播放时,我想传递一个范围

//this is called on a loop and I want to avoid duplicates
     internal ExampleMember PopulateMember()
    {
        var member = new ExampleMember();

        member.gender = RandomGenNumber.Next(0, 100) < 42 ? "M" : "F";

        member.personalityTypeId = RandomGenNumber.Next(1, 45);

        member.age = RandomGenNumber.Next(20, 80);

        ...

我在这里阅读了几十篇文章,但我找不到范围的例子。

生成数字的字节方式看起来很干净,但我不能让它在一个范围内工作。我应该通过Ints还是加倍并乘以?或者如何在具有开始和结束范围的Next的重载中使用该缓冲区值?

1 个答案:

答案 0 :(得分:2)

inst.Next()应为inst.Next(low, high)。就这样。播种部分不需要触摸。将其移动到辅助方法(例如static Random GetThreadStaticRandom())。