为什么此C#控制台应用程序多次输出相同的字符串?

时间:2019-02-01 02:19:03

标签: c# string console console-application

我正在尝试创建一个唯一的代码生成器,并且正在使用这里找到的解决方案:How can I generate random alphanumeric strings?

当我运行该应用程序时,控制台将输出相同的字符串8次,而不是输出8个不同的代码。但是,如果我通过在每次写入之间添加睡眠(20毫秒)来减慢应用速度,则代码将输出8个不同的字符串。

class Program
{
    static void Main(string[] args)
    {
        // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
        for (int i = 0; i < 8; i++)
        {
            string code = GetUniqueCode(8);
            Console.WriteLine(code);
        }
        Console.ReadKey();
    }

    private static string GetUniqueCode(int length)
    {
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var stringChars = new char[length];
        var random = new Random();

        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[random.Next(chars.Length)];
        }

        var finalString = new String(stringChars);
        return finalString;
    }
}

0 个答案:

没有答案