-1

我试图编写一个随机字符串数组算法,但我得到一个空引用错误..我不知道为什么..

public static string[] arrRandomized;
public static string[] ShuffleWords(string[] Words)
{
    Random generator = new Random();
    for (int i=0;i < Words.Length; i++) {
        int pos = generator.Next(Words.Length);
        Console.WriteLine(Words[pos]); // I SEE RANDOM ITEM
        Console.Read(); // NULL REFERENCE ERROR AFTER THIS
        if (Words[pos] != null)
        {
            arrRandomized[i] = Words[pos];
            //remove item at pos so I get no duplicates
            Words[pos] = null;
        }
    }

我不想使用 ArrayList,我有我的理由,但那是题外话我只想知道这怎么不起作用:/ 谢谢

4

2 回答 2

3

我认为你应该初始化arrRandomized

arrRandomized = new string[Words.Length];
于 2012-11-10T18:38:53.187 回答
0

你的 arrRandomized 永远不会被初始化。我还建议您返回一个数组而不是使用静态引用,因为随后对该方法的调用将更改对 arrRandomized 的所有引用。

public static string[] ShuffleWords(string[] Words)
{    
    string[] arrRandomized = new string[Words.Length];
    Random generator = new Random();
    for (int i=0;i < Words.Length; i++) 
    {
        int pos = generator.Next(Words.Length);
        Console.WriteLine(Words[pos]); // I SEE RANDOM ITEM
        Console.Read(); // NULL REFERENCE ERROR AFTER THIS
        if (Words[pos] != null)
        {
            arrRandomized[i] = Words[pos];
            //remove item at pos so I get no duplicates
            Words[pos] = null;
        }
    }
    return arrRandomized;
}
于 2012-11-10T18:40:22.497 回答