ASP.NET 伪随机数函数避免重复一例

对于 ASP.NET 的伪随机数函数 System.Random(seed),每次用不同seed,则可避免产生的随机数重复,尤其在反复调用Random()时。
可设置一个页面内变量iseed,每次调用Random(iseed)后递增iseed。经实际测试,产生的随机字串不会重复。CSharp 主要代码如下:

// page1.aspx.cs
internal class mypara1
{
     internal static int iseed = 0;
}


internal class myclass1
{
    internal static string randomstr(int len1)
    {
        // in   len
        // out  randomstr
        string chars = "ABCDEFGHIJKLMNOPQRSTUWVXYZabcdefghijklmnopqrstuvwxyz";
        Random random = new Random(mypara1.iseed);
        mypara1.iseed++;
        string strs = string.Empty;
        for(int i=0; i<len1; i++)
        {
           strs += chars[random.Next(chars.Length)];
        }
        return strs;
    }
}

  

原文地址:https://www.cnblogs.com/xyyztx/p/14586521.html