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

遭遇StackOverFlowException错误,求排查C#国家查询程序问题

问题根源:循环实例化引发StackOverflowException

老兄,你的核心问题一眼就能揪出来——错误的类继承+循环实例化导致栈被撑爆了!

你看代码里的类结构:Country : CountryList,也就是Country继承自CountryList。但在CountryList类里,你又声明了Country memberName = new Country();。这直接形成了死循环:

  • 创建CountryList对象时,会初始化memberName,也就是new Country()
  • 但Country是CountryList的子类,创建子类对象必须先初始化父类(CountryList)
  • 初始化父类时又会再次创建Country对象,无限重复这个过程,直到栈溢出,抛出StackOverflowException

这就是你删了很多代码还报错的原因,这个继承和实例化的逻辑完全搞反了!

其他需要修复的小问题

除了核心的栈溢出,代码里还有几个明显的逻辑错误:

  • StreamReader资源泄漏:你把filePath声明为类成员变量,每次调用方法都会重复打开文件,还没释放资源,应该用using语句自动管理。
  • while循环条件错误:(finished = false)是赋值操作,不是判断,应该写成(finished == false),不然循环会一直跑停不下来。
  • 返回值无效:你返回countryItems.ToString(),但List的ToString()只会返回类型名,不会返回列表内容,得用string.Join拼接。
  • 类关系混淆:Country是单个国家的实体,CountryList是管理多个国家的集合类,应该是组合关系,不是继承关系。
修复后的代码示例
using System;
using System.Collections.Generic;
using System.IO;

class CountryProgram
{
    static void Main(string[] args)
    {
        CountryList printSearch = new CountryList();
        printSearch.findAll();
    }
}

// 管理国家列表的集合类
public class CountryList
{
    private readonly string _filePath = "countries.txt";
    
    public List<string> CountryItems { get; private set; } = new List<string>();
    public List<string> CapitalItems { get; private set; } = new List<string>();
    public List<string> PopulationItems { get; private set; } = new List<string>();
    public List<string> AllItems { get; private set; } = new List<string>();

    // 读取用户输入并处理搜索逻辑
    public string GetString()
    {
        Console.WriteLine("Enter the first letter of the countries you wish to search: ");
        string userInput = Console.ReadLine();
        
        bool hasUpperCase = false;
        List<char> upperChars = new List<char>();
        
        foreach (char item in userInput)
        {
            if (Char.IsUpper(item))
            {
                upperChars.Add(item);
                hasUpperCase = true;
            }
        }

        if (!hasUpperCase)
        {
            Console.WriteLine("Please enter one character in capital letters");
            Console.ReadLine();
            return string.Empty;
        }

        // 使用using自动释放StreamReader资源
        using (StreamReader reader = new StreamReader(_filePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                // 这里可以根据countries.txt的实际格式分割数据,比如国家/首都/人口
                CountryItems.Add($"Match: {line}");
            }
        }

        // 拼接列表内容返回
        return string.Join(Environment.NewLine, CountryItems);
    }

    public void findAll()
    {
        string result = GetString();
        if (!string.IsNullOrEmpty(result))
        {
            Console.WriteLine(result);
        }
        Console.ReadLine();
    }
}

// 单个国家的实体类,无需继承CountryList
public class Country
{
    public string Name { get; set; }
    public string Capital { get; set; }
    public int Population { get; set; }
    public bool StartsWith { get; set; }
    public bool CapitalHas { get; set; }
    public bool LesserPopulation { get; set; }

    public Country() { }

    public Country(string name, string capital, int population)
    {
        Name = name;
        Capital = capital;
        Population = population;
    }
}
关键修改说明
  • 移除错误继承:Country不再继承CountryList,改成独立的实体类,CountryList负责管理数据,这才是合理的类结构。
  • 解决循环实例化:CountryList里不再直接实例化Country,彻底切断死循环。
  • 优化资源管理:用using语句处理StreamReader,避免文件占用和资源泄漏。
  • 修正逻辑细节:把循环里的赋值改成判断,用string.Join正确返回列表内容,同时调整了变量命名符合C#规范。

这样修改后,StackOverflowException的问题就彻底解决了,你可以再根据countries.txt的实际格式,完善国家匹配的具体逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:24:55