每个对象都有相同的数组

Each object have the same array

我在多个相同对象 class 中改组数组时遇到问题。
我在构造函数调用中使用函数 void shuffle()
打印我的 dataCharset 数组后事实证明,每个对象都有相同的随机排列数组。

我在控制台应用程序中使用 .net framework 4.8。
我试过使用临时数组,然后将其随机复制到 dataCharset 数组(这是我需要随机播放的目标数组)。

char[] dataCharset =
{
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
    '!', '$', '#', '@', '-'
};

void shuffle()
{
    Random random = new Random();

    for (int i = 0; i < dataLength; i++)
    {
        int index = random.Next(0, dataLength);
        char temp = dataCharset[index];
        dataCharset[index] = dataCharset[i];
        dataCharset[i] = temp;
    }
}

构造函数看起来像:

public Guesser()
{
    dataLength = dataCharset.Length;
    shuffle();
    Console.WriteLine(dataCharset);
}

还有我创建对象的主文件
猜猜是我的class

Guesser guesser1 = new Guesser();
Guesser guesser2 = new Guesser();
Guesser guesser3 = new Guesser();
Guesser guesser4 = new Guesser();

如果我使用 'new' 关键字创建对象,为什么每个对象都有相同的数组? 我希望每个对象都有自己的随机数组。

有可能(尽管不像我通常看到的那么明显)您的代码速度足够快,以至于您对 Random 对象使用相同的种子。尝试将其设为 class:

的静态 属性
static Random random = new Random();

void shuffle()
{
    for (int i = 0; i < dataLength; i++)
    {
        int index = random.Next(0, dataLength);
        char temp = dataCharset[index];
        dataCharset[index] = dataCharset[i];
        dataCharset[i] = temp;
    }
}