在 C# 中使用随机名称生成器的 StackOverflow

StackOverflow with Random Name Generator in C#

using System;


namespace npcnames

{
    class Program
{



    static string RandomVowel()
    {
        Random rand = new Random(); 
        string[] Vowels = new string[5] { "a", "e", "i", "o", "u" };
        int index = rand.Next(Vowels.Length); 
        string Vowel = Vowels[index]; 

        return Vowel;
    }

    static string RandomConsonant()
    {
        Random rand = new Random(); 
        string[] Consonants = new string[21] { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" };
        int index = rand.Next(Consonants.Length); 
        string Consonant = Consonants[index]; 

        return Consonant;
    }

    static string MaleName()
    {
        string malename = RandomConsonant() + RandomVowel() + RandomConsonant() + RandomVowel() + RandomConsonant();
        return MaleName();
    }

    static string FemaleName()
    {
        string femalename = RandomVowel() + RandomConsonant() + RandomVowel() + RandomConsonant() + RandomVowel();
        return FemaleName();
    }

    static void generateFemaleName(int from, int to, int step)
    {
       

        for (int a = from; a <= to; a = a + step)
        {
         
            Console.WriteLine("Female:");
            Console.WriteLine(a + FemaleName());
        }


    }

    static void generateMaleName(int from, int to, int step)
    {
        

        for (int b = from; b <= to; b = b + step)
        {

            Console.WriteLine("Male:");
            Console.WriteLine(b + MaleName());
        }


    }






    static void Main(string[] args)
    {
        generateFemaleName(1,10,1);
        Console.WriteLine();
        generateMaleName(1,10,1);

    }
}

大家好,我是编码和所有方面的新手,如果有人能帮助我解决这个问题,我将不胜感激。问题是在我的代码中,我不断出现堆栈溢出,我不知道如何防止它正常执行我的程序。该程序的目的是在每个 10 个列表中生成随机选择的元音和辅音的男性和女性名称。

问题在这里:

static string FemaleName()
{
   string femalename = RandomVowel() + RandomConsonant() + RandomVowel() + RandomConsonant() + RandomVowel();
   return FemaleName(); //  <== bam!
}

变化:

return FemaleName();

至:

return femalename;

简而言之,该方法不断地调用自身。 MaleName().

完全一样

此外,在我们修复问题时,Random 初始化应该在方法之外:

private static Random rand = new Random(); 

static string RandomConsonant()
{
   string[] Consonants = new string[21] { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" };
   int index = rand.Next(Consonants.Length); 
   string Consonant = Consonants[index]; 

   return Consonant;
}

如果你改变它会被修复

return MaleName(); 

return malename;

也一样
return FemaleName(); 

return femalename;

就是你要return的字符串。