You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现随机姓名生成器触发StackOverflow错误如何解决

C#随机姓名生成程序StackOverflow错误修复

核心问题说明

  • 无限递归触发栈溢出:你的MaleName()、FemaleName()方法生成完姓名字符串后,没有返回构造好的字符串变量,反而重新调用方法自身,这种无终止条件的递归会无限占用调用栈空间,最终触发StackOverflow错误,这是报错的直接原因。
  • 随机数生成逻辑缺陷:每次获取元音、辅音时都重新实例化Random对象,Random默认以系统时间作为随机种子,短时间高频调用会因种子相同生成完全一致的随机值,导致生成的姓名重复率极高。

修复方案

直接修改对应方法的返回逻辑,同时将Random对象改为全局静态实例即可,修复后完整代码如下:

using System;

namespace npcnames
{
    class Program
    {
        // 全局Random实例,只初始化一次,保证随机值正常
        private static Random rand = new Random();
        static string RandomVowel()
        {
            string[] Vowels = new string[5] { "a", "e", "i", "o", "u" };
            int index = rand.Next(Vowels.Length); 
            return Vowels[index];
        }

        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); 
            return Consonants[index];
        }

        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个女性姓名、10个男性姓名,无栈溢出错误,随机生成逻辑正常。

内容的提问来源于stack exchange,提问作者Mindo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:24:07