号外号外: 原[图享网]更名为 码友网(codedefault.com) 啦,感谢大家一路上的陪伴与支持。代码的世界里,码友网与大家一起同行!

.NET[C#]生成指定区间内的惟一(不重复)的随机数字

C#开发 作者: Rector 900阅读 0评论 0收藏 收藏本文 编辑

郑重申明:本文未经许可,禁止任何形式转载

方式一

private static readonly Random random = new Random(); 
private static readonly object syncLock = new object(); 
public static int RandomNumber(int min, int max)
{
    lock(syncLock) { // synchronize
        return random.Next(min, max);
    }
}

方式二

public static class StaticRandom
{
    private static int seed;

    private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
        (() => new Random(Interlocked.Increment(ref seed)));

    static StaticRandom()
    {
        seed = Environment.TickCount;
    }

    public static Random Instance { get { return threadLocal.Value; } }
}

调用方式:StaticRandom.Instance.Next(1, 100);

方式三

public class RandomNumber : IRandomNumber
{
    private static readonly Random Global = new Random();
    [ThreadStatic] 
    private static Random _local;

    public int Next(int max)
    {
        var localBuffer = _local;
        if (localBuffer == null) 
        {
            int seed;
            lock(Global) seed = Global.Next();
            localBuffer = new Random(seed);
            _local = localBuffer;
        }
        return localBuffer.Next(max);
    }
}

方式四

namespace mySpace
{
    public static class Util
    {
        private static rnd = new Random();
        public static int GetRandom()
        {
            return rnd.Next();
        }
    }
}

调用方式: var i = Util.GetRandom();

阅读了该文章的人还浏览了...

本文永久链接码友网 » .NET[C#]生成指定区间内的惟一(不重复)的随机数字

发布于: 2017-12-28 09:00:00
分享扩散: